// Get /appointments
{
"per_page": 10, "page": 1, "total": 50,
"appointments": [
{ "title": "Ms. Kitty Hairball Treatment", "cankelled": false, "identifier": 1 }
]
} The server team is at it again, but this time they at least have a good reason: they want to start paginating appointments instead of just returning all of them when we fetch the Appointmentscollection. No problem. We've been here before. Take a look at the JSON the server is responding with below, and then modify the parse function to set properties on the collection instance for per_pagetotal, and page.
var Appointments = Backbone.Collection.extend({
parse: function(response){
this.per_page = response.per_page;
this.total = response.total;
this.page = response.page;
return response;
}
});

Fantastic work! Now to finish the job, just return the appointments array from the parse function, instead of the entire response.

// Get /appointments
{
"per_page": 10, "page": 1, "total": 50,
"appointments": [
{ "title": "Ms. Kitty Hairball Treatment", "cankelled": false, "identifier": 1 }
]
}
var Appointments = Backbone.Collection.extend({
parse: function(response){
this.perPage = response.per_page;
this.page = response.page;
this.total = response.total;
response = response.appointments
return response;
}
});

The server team has implemented a feature for limiting the appointments pulled down based on the appointment date. In the code below, update the fetch call to pass an extra param so that the URL is like:/appointments?since=2013-01-01

var appointments = new Appointments();
appointments.fetch({data: {since: '2013-01-01'}});

We can limit the number of appointments returned by passing in a per_page parameter also. Go ahead and construct the fetch call below to create a URL that looks like /appointments?since=2013-01-01&per_page=10

var appointments = new Appointments();
appointments.fetch({data: {since: "2013-01-01", per_page: 10}});

Let's start to implement this feature by adding a template to the AppointmentListView below. The template should have a link that looks like this: <a href="#/appointments/p<%= page %>/pp<%= per_page %>">View Next</a>

var AppointmentListView = Backbone.View.extend({
//Using template display the Next page
template: _.template('<a href="#/appointments/p<%= page %>/pp<%= per_page %>">View Next</a>'),
initialize: function(){
this.collection.on('reset', this.render, this);
},
render: function(){
thi.$el.empty();
this.collection.forEach(this.addOne, this);
},
addOne: function(model){
var appointmentView = new AppointmentView({model: model});
appointmentView.render();
this.$el.append(appointmentView.el);
}
});

let's add some code in the render function to append the generated HTML from the template into the AppointmentListView $el. Make sure you pass in thepage and per_page properties to the template function, getting those values fromthis.collection.page + 1 and this.collection.per_page respectively.

var AppointmentListView = Backbone.View.extend({
template: _.template('<a href="#/appointments/p<%= page %>/pp<%= per_page %>">View Next</a>'),
initialize: function(){
this.collection.on('reset', this.render, this);
},
render: function(){
this.$el.empty();
this.collection.forEach(this.addOne, this);
this.$el.append(this.template({page:this.collection.page + 1, per_page:this.collection.per_page}));
},
addOne: function(model){
var appointmentView = new AppointmentView({model: model});
appointmentView.render();
this.$el.append(appointmentView.el);
}
});

Now that we are rendering the link, we need to implement the route to handleappointments/p:page/pp:per_page and have the route function fetch the new appointments based on the parameters. Name this new function page.

var AppRouter = new (Backbone.Router.extend({
routes: {
"": "index",
"appointments/p:page/pp:per_page": "page"
},
initialize: function(options){
this.appointmentList = new AppointmentList();
},
index: function(){
var appointmentsView = new AppointmentListView({collection: this.appointmentList});
appointmentsView.render();
$('#app').html(appointmentsView.el);
this.appointmentList.fetch();
},
page: function(page, per_page){
this.appointmentList.fetch({data:{page: page, per_page: per_page}});
}
}));

Our appointments are being rendered in a pretty haphazard way. Dr. Goodparts is very chronological, so we need to always have our appointments sorted by the date. Add the code below to accomplish this.

var Appointments = Backbone.Collection.extend({
comparator: "date"
});
var app1 = new Appointment({date: "2013-01-01"});
var app2 = new Appointment({date: "2013-02-01"});
var app3 = new Appointment({date: "2013-01-15"});
var app4 = new Appointment({date: "2013-01-09"});
var appointments = new Appointments();
appointments.add(app1);
appointments.add(app2);
appointments.add(app3);
appointments.add(app4);

Dr. Goodparts just sent us this email "Love the new sorting, but please flip it and reverse it", Update the comparator below to sort by date in reverse order

var Appointments = Backbone.Collection.extend({
comparator: function(ap1, ap2){
return ap1.get('date') < ap2.get('date');
}
});

implement a function on the collection to count up the number of cancelled appointments. Implement this function in the collection class below and call it cancelledCount.

var Appointments = Backbone.Collection.extend({
cancelledCount: function(){
return this.where({'cancelled': true}).length;
}
});

----------------------------Final Code------------------------

var Appointments = Backbone.Collection.extend({
// comparator: "date",
comparator: function(ap1, ap2){
return ap1.get('date') < ap2.get('date');
},
cancelledCount: function(){
return this.where({'cancelled': true}).length;
},
parse: function(response){
this.perPage = response.per_page;
this.page = response.page;
this.total = response.total;
response = response.appointments
return response;
}
});
var appointments = new Appointments();
appointments.fetch({data: {since: "2013-01-01", per_page: 10}});
var AppointmentListView = Backbone.View.extend({
template: _.template('<a href="#/appointments/p<%= page %>/pp<%= per_page %>">View Next</a>'),
initialize: function(){
this.collection.on('reset', this.render, this);
},
render: function(){
this.$el.empty();
this.collection.forEach(this.addOne, this);
this.$el.append(this.template({page:this.collection.page + 1, per_page:this.collection.per_page}));
},
addOne: function(model){
var appointmentView = new AppointmentView({model: model});
appointmentView.render();
this.$el.append(appointmentView.el);
}
});
var AppRouter = new (Backbone.Router.extend({
routes: {
"": "index",
"appointments/p:page/pp:per_page": "page"
},
initialize: function(options){
this.appointmentList = new AppointmentList();
},
index: function(){
var appointmentsView = new AppointmentListView({collection: this.appointmentList});
appointmentsView.render();
$('#app').html(appointmentsView.el);
this.appointmentList.fetch();
},
page: function(page, per_page){
this.appointmentList.fetch({data:{page: page, per_page: per_page}});
}
}));

[Backbone] Parse JSON on Collection的更多相关文章

  1. Guzzle Unable to parse JSON data: JSON_ERROR_SYNTAX - Syntax error, malformed JSON

    项目更新到正式平台时,出现Guzzle(5.3) client get请求出现:Unable to parse JSON data: JSON_ERROR_SYNTAX - Syntax error, ...

  2. JSON.parse() JSON.stringify() eval() jQuery.parseJSON() 的区别

    http://www.jb51.net/article/81880.htm    :   jQuery.parseJSON(jsonString) : 将格式完好的JSON字符串转为与之对应的Java ...

  3. 使用JSON.parse(),JSON.stringify()实现对对象的深拷贝

    根据不包含引用对象的普通数组深拷贝得到启发,不拷贝引用对象,拷贝一个字符串会新辟一个新的存储地址,这样就切断了引用对象的指针联系. 测试例子: var test={ a:"ss", ...

  4. JSON.parse(JSON.stringify(obj))

    JSON.parse(JSON.stringify(obj)实现数组的深拷贝 利用JSON.stringify 将js对象序列化(JSON字符串),再使用JSON.parse来反序列化(还原)js对象

  5. JSON.parse JSON.stringify

    JSON.stringify() undefined 值.函数或者XML值会被忽略 数组当中含有 undefined值,函数或XML值,该数组中的这些值将会被当成 null 正则对象会被转成空对象 J ...

  6. parse.JSON()报错是什么原因?

    哪里出错了? JSON.parse() 会把一个字符串解析成 JSON 对象.如果字符串书写正确,那么其将会被解析成一个有效的 JSON,但是这个字符串被检测出错误语法的时候将会抛出错误. 示例 JS ...

  7. 【Immutable】拷贝与JSON.parse(JSON.stringify()),深度比较相等与underscore.isEqual(),性能比较

    样本:1MB的JSON文件,引入后生成500份的一个数组: 结果如下: 拷贝性能: JSON.parse(JSON.stringify()) 的方法:2523.55517578125ms immuta ...

  8. JSON.parse(JSON.stringify()) 实现对对象的深拷贝

    JSON.parse(JSON.stringify(obj))我们一般用来深拷贝,其过程说白了 就是利用JSON.stringify 将js对象序列化(JSON字符串),再使用JSON.parse来反 ...

  9. this.treeData = JSON.parse(JSON.stringify(this.d)) 树的序列化反序列化

    this.treeData = JSON.parse(JSON.stringify(this.d))

随机推荐

  1. collection 和 collections

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha collection 是集合的意思. 集合 是 集合类的上级接口, 比如 set 和 l ...

  2. Three.js 类的粗略总结和实现

    类 1.Cameras 照相机,包括很多种类型的摄像机类,包括正交类型和投影类型的摄像机 2.Core 核心对象 3.Lights 光照,包括点光,环境光,镜面光等等 4.Loaders 专门用来加载 ...

  3. JQ中get()与eq()的区别

    .eq() : 减少匹配元素的集合,根据index索引值,精确指定索引对象. .get() : 通过检索匹配jQuery对象得到对应的DOM元素. 同样是返回元素,那么eq与get有什么区别呢? eq ...

  4. 彻底解决每次打开visio都提示windows正在配置visio的问题

    出现这个提示windows正在配置XXX软件的问题,是由于在安装一个新的版本时,之前那个版本的office没有完全卸载,注册表内有残留. 最简单的方式,并不是 把HKEY_CURRENT_USER\S ...

  5. PostgreSQL各命令行工具功能说明

    I. SQL 命令 II. PostgreSQL 客户端应用 clusterdb -- 聚簇一个PostgreSQL数据库 createdb -- 创建一个新的PostgreSQL数据库 create ...

  6. both, either, neither的用法

    http://www.yywords.com/Article/200806/347.html  1. 这三个词都用来谈论两者:both 意为“(两者)都”,either意为“(两者中)任意一个”,ne ...

  7. MYSQL 源码- 淘宝数据库研发组

    http://mysql.taobao.org/index.php?title=%E8%B5%84%E6%96%99%E5%85%B1%E4%BA%AB

  8. iOS中bundle的意义

    什么是bundle? bundle就是一个文件夹,按照一定标准组织的目录结构.每个iOS APP至少有一个main bundle,这个main bundle包含了app的二进制代码及任何你用到的资源, ...

  9. mac 下 outlook 邮箱 服务器端口设置

  10. cocos2d-x 3.0 事件处理

    參考文章: star特530的CSDN博客:http://blog.csdn.net/star530/article/details/18325493 https://github.com/chuko ...