[Backbone] Parse JSON on Collection
// 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 theAppointmentscollection. No problem. We've been here before. Take a look at the JSON the server is responding with below, and then modify theparsefunction to set properties on the collection instance forper_page,total, andpage.
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的更多相关文章
- 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, ...
- JSON.parse() JSON.stringify() eval() jQuery.parseJSON() 的区别
http://www.jb51.net/article/81880.htm : jQuery.parseJSON(jsonString) : 将格式完好的JSON字符串转为与之对应的Java ...
- 使用JSON.parse(),JSON.stringify()实现对对象的深拷贝
根据不包含引用对象的普通数组深拷贝得到启发,不拷贝引用对象,拷贝一个字符串会新辟一个新的存储地址,这样就切断了引用对象的指针联系. 测试例子: var test={ a:"ss", ...
- JSON.parse(JSON.stringify(obj))
JSON.parse(JSON.stringify(obj)实现数组的深拷贝 利用JSON.stringify 将js对象序列化(JSON字符串),再使用JSON.parse来反序列化(还原)js对象
- JSON.parse JSON.stringify
JSON.stringify() undefined 值.函数或者XML值会被忽略 数组当中含有 undefined值,函数或XML值,该数组中的这些值将会被当成 null 正则对象会被转成空对象 J ...
- parse.JSON()报错是什么原因?
哪里出错了? JSON.parse() 会把一个字符串解析成 JSON 对象.如果字符串书写正确,那么其将会被解析成一个有效的 JSON,但是这个字符串被检测出错误语法的时候将会抛出错误. 示例 JS ...
- 【Immutable】拷贝与JSON.parse(JSON.stringify()),深度比较相等与underscore.isEqual(),性能比较
样本:1MB的JSON文件,引入后生成500份的一个数组: 结果如下: 拷贝性能: JSON.parse(JSON.stringify()) 的方法:2523.55517578125ms immuta ...
- JSON.parse(JSON.stringify()) 实现对对象的深拷贝
JSON.parse(JSON.stringify(obj))我们一般用来深拷贝,其过程说白了 就是利用JSON.stringify 将js对象序列化(JSON字符串),再使用JSON.parse来反 ...
- this.treeData = JSON.parse(JSON.stringify(this.d)) 树的序列化反序列化
this.treeData = JSON.parse(JSON.stringify(this.d))
随机推荐
- BZOJ.2738.矩阵乘法(整体二分 二维树状数组)
题目链接 BZOJ 洛谷 整体二分.把求序列第K小的树状数组改成二维树状数组就行了. 初始答案区间有点大,离散化一下. 因为这题是一开始给点,之后询问,so可以先处理该区间值在l~mid的修改,再处理 ...
- 【洛谷】3469:[POI2008]BLO-Blockade【割点统计size】
P3469 [POI2008]BLO-Blockade 题意翻译 在Byteotia有n个城镇. 一些城镇之间由无向边连接. 在城镇外没有十字路口,尽管可能有桥,隧道或者高架公路(反正不考虑这些).每 ...
- Java中日期类型和mysql中日期类型进行整合
1. java与mysql中日期.时间类型总结: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 mysql(版本:5.1.50)的时间日期类型如下: da ...
- 无法将类型为“Microsoft.Office.Interop.Excel.ApplicationClass”的COM 对象强制转换为接口类型“Microsoft.Office.Interop.Excel._Application”
报错内容如下: 无法将类型为“Microsoft.Office.Interop.Excel.ApplicationClass”的COM对象强制转换为接口类型“Microsoft.Office.Inte ...
- vue各生命周期适合做的业务逻辑
一.实际项目中使用最多的Vue生命周期大概是 created mounted updated 二.各自适合做的业务逻辑 1. created 相当于是页面刚开始加载的状态,此时不能操作实例的 ...
- 在当前的webview中跳转到新的url 使用WebView组件显示网页
如果希望点击链接由自己处理,而不是新开Android的系统browser中响应该链接.给WebView加一个事件监听对象(WebViewClient)并重写其中的一些方法:shouldOverride ...
- Disable File System Redirector For Windows x64 (Python recipe)(转)
This disables the Windows File System Redirector.When a 32 bit program runs on a 64 bit operating sy ...
- UVa11187
莫勒定理,证明如下: 请结合下图看代码: #include <iostream> #include <math.h> #include <iomanip> usin ...
- 对话框上动态控件的创建、在Picture Control控件上显示图片
1 MFC对话框之上的动态控件的创建 对话框上的控件是MFC类的一个具体对象. 当在对话框之上使用静态控件时,可以根据类向导来为每个控件添加消息.响应函数以及变量. 当需要在对话框中动态的创建某个控 ...
- 如何开启解决android studio的模拟器的问题
来自:http://jingyan.baidu.com/article/03b2f78c0a19e75ea237ae24.html 有的时候因为电脑系统或者是安装的一些问题我们可能需要对症下药的解决模 ...