// 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. lnmp环境一键搭建及卸载

    系统需求: CentOS/Debian/Ubuntu Linux系统 需要2GB以上硬盘剩余空间 128M以上内存,OpenVZ的建议192MB以上(小内存请勿使用64位系统) VPS或服务器必须已经 ...

  2. CentOS的利手:“Screen”一个可以在多个进程之间多路复用一个物理终端的窗口管理器

    你是不是经常需要远程登录到Linux服务器?你是不是经常为一些长时间运行的任务头疼?还在用 nohup 吗?那 么来看看 screen 吧,它会给你一个惊喜! 你是不是经常需要 SSH 或者 tele ...

  3. hdu 4548 初始化+二分 *

    题意:小明对数的研究比较热爱,一谈到数,脑子里就涌现出好多数的问题,今天,小明想考考你对素数的认识.问题是这样的:一个十进制数,如果是素数,而且它的各位数字和也是素数,则称之为“美素数”,如29,本身 ...

  4. cocos2dx 3.0 中文 iconv 转换函数

    //#include <string> #pragma once #include "cocos2d.h"; #include "iconv\include\ ...

  5. SMB协议概述

    一.概述 SMB(Server Message Block)是由微软开发的一种软件程序级的网络传输协议,主要用来使得一个网络上的计算机共享计文件.打印机.串行端口和通讯等资源.它也提供认证的进行进程间 ...

  6. [JAVA] JAVA JDK 安装配置

    JDK 安装 下载安装 下载JDK 从oracle官方网站下载并安装JDK. 下载使用文档 从oracle官方网站下载使用帮助文档. 安装库源文件 源文件位于安装目录的 /Library/Java/J ...

  7. Is Usb Drive () ? DeviceIoControl, IOCTL_STORAGE_QUERY_PROPERTY

    http://banderlogi.blogspot.com/2011/06/enum-drive-letters-attached-for-usb.html typedef enum _STORAG ...

  8. 腾讯旗下网站的很多URL都包含“cgi-bin”,是什么意思?他们后台用什么语言?

    cgi-bin 这很有可能说明后台是C/C++写的. 动态Web技术刚出来的时候, 服务器调用本地应用程序处理http请求的技术. 通常是C/C++程序. 后来有了新的web开发技术后这类用的就比较少 ...

  9. 数据库中间件OneProxy and onemysql

    http://blog.itpub.net/28944233/cid-176181-list-1/ http://www.onexsoft.com/ 官网 http://pan.baidu.com/s ...

  10. lucene.net 3.0.3、结合盘古分词进行搜索的小例子(分页功能)

    转自:http://blog.csdn.net/pukuimin1226/article/details/17558247 添加:2013-12-25 更新:2013-12-26 新增分页功能. 更新 ...