- 浏览: 9106 次
- 性别:
- 来自: 南京
最新评论
-
since1027:
Backbone系列教程的最后一章了,希望对Backbone入 ...
Part 8: Understanding Backbone.js Events
In this article we will discuss about Backbone.js collections. We will see how we can use collections to manipulate a group of models and how we can use restul API to easily fetch and save collections.
Background
Every application need to create a collection of models which can be ordered, iterated and perhaps sorted and searched when a need arises. Keeping this in mind, backbone also comes with a collection type which makes dealing with collection of models fairly easy and straight forward.
Link to complete series:
Using the code
Let us start looking at the backbone collections in details.
Creating a collection
Creating a backbone collection is similar to creating a model. We just need to extend the backbone’s collection class to create our own collection. Let us continue working with the same example where we created a Book model and lets try to create a simple BooksCollection.
This collection will hold the Book model we have created in our previous articles.
Specifying the model for a collection
To specify which model this collection should hold, we need to specify/override the model property of the collection class.
Once we specify the model property of a collection what will happen internally is that whenever we create this collection, internally it will create an array of the specified models. Then all the operations on this collection object will result in the actual operations on that array.
Instantiating a collection
A collection can be instantiated by using the new keyword. We can create an empty collection and then add the model objects to it later or we can pass a few model objects in the collection while creating it.
Adding models to collection
To add an item to a collection, we can use the add method on the collection. The important thing to notice here is that if the item with the same id exist in the collection, the add will simply be ignored.
Now there might be a scenario where we actually want to update an existing added model in a collection. If that is the case, then we need to pass the {merge: true} option in the add function.
Another important point to consider here is that the collection keep a shallow copy of the actual models. So if we change a model attribute after adding it to a collection, the attribute value will also get changed inside the collection.
Also, if we want to add multiple models, we can do that by passing the model array in the add method.
It is also possible to add the model at a specific index in the collection. To do this we need to pass the {at: location} in the add options.
Note: push and unshift function can also be used to add models to collection.
Removing models from collection
To remove the model from the collection, we just need to call the remove method on the collection. The remove method simply removes this model from the collection.
Also, if we want to empty the model, we can call the reset method on the collection.
It is also possible to reset a collection and populate it with new models by passing an array of models in the reset function.
Note: pop and shift function can also be used to remove model from collection.
Finding the number of items in collection
The total number of items in a collection can be found using the length property.
Retrieving models from collection
To retrieve a model from a specific location, we can use the at function by passing a 0 based index.
Alternatively, to get the index of a known model in the collection, we can use the indexOf method.
We can also retreive a model from a collection if we know its id or cid. this can be done by using the get function.
If we want to iterate through all the models in a collection, we can simply use the classic for loop or the each function provided by collections which is very similar to the foreach loop of underscore.js.
Listening to collection events
Backbone collection raises events whenever an item is added removed to updated in the collection. We can subscribe to these events by listening to add, remove and change event respectively. Let us subscribe to these events in our model to see how this can be done.
The set function
The set function can be used to update all the items in a model. If we use set function, it will check for all the existing models and the models being passed in set. If any new model is found in the models being passed, it will be added. If some are not present in the new models list, they will be removed. If there are same models, they will be updated.
The above shown set function will call remove for book2, change for book3 and add for book5.
Sorting a collection
Backbone keeps all the models in the collection in a sorted order. We can call the sort function to forcefully sort it again but the models are always stored in sorted order. By default these items are sorted in the order they are added to the collection. But we can customize this sorting behavior by providing a simple comparator to our collection.
What this comparator does is that it overrides the default sorting behavior by specifying the attribute that should be used for sorting. We can even used a custom expression in this comparator too.
Fetch collection using HTTP REST service
To be able to fetch the collection from the server, we need to specify the url for the api that returns the collection.
Now to fetch the collection from the server, lets call the fetch function.
Save collection using HTTP REST service
Lets see how we can save the items of a collection on the server.
In the above code we are calling save on each model object. this can be improved by either overriding the sync function on a collection or perhaps creating a wrapper model for collection and saving the data using that.
Note: The web api code for can be downloaded from the previous article of the series.
Point of interest
In this article we have discusses about the backbone collections. This has been written from a beginner’s perspective. I hope this has been informative.
原文链接:http://rahulrajatsingh.com/2014/07/backbone-tutorial-part-5-understanding-backbone-js-collections/
Background
Every application need to create a collection of models which can be ordered, iterated and perhaps sorted and searched when a need arises. Keeping this in mind, backbone also comes with a collection type which makes dealing with collection of models fairly easy and straight forward.
Link to complete series:
- Part 1: Introduction to Backbone.Js
- Part 2: Understanding the basics of Backbone Models
- Part 3: More about Backbone Models
- Part 4: CRUD Operations on BackboneJs Models using HTTP REST Service
- Part 5: Understanding Backbone.js Collections
- Part 6: Understanding Backbone.js Views
- Part 7: Understanding Backbone.js Routes and History
- Part 8: Understanding Backbone.js Events
Using the code
Let us start looking at the backbone collections in details.
Creating a collection
Creating a backbone collection is similar to creating a model. We just need to extend the backbone’s collection class to create our own collection. Let us continue working with the same example where we created a Book model and lets try to create a simple BooksCollection.
var BooksCollection = Backbone.Collection.extend({ });
This collection will hold the Book model we have created in our previous articles.
var Book = Backbone.Model.extend({ defaults: { ID: "", BookName: "" }, idAttribute: "ID", urlRoot: 'http://localhost:51377/api/Books' });
Specifying the model for a collection
To specify which model this collection should hold, we need to specify/override the model property of the collection class.
var BooksCollection = Backbone.Collection.extend({ model: Book, });
Once we specify the model property of a collection what will happen internally is that whenever we create this collection, internally it will create an array of the specified models. Then all the operations on this collection object will result in the actual operations on that array.
Instantiating a collection
A collection can be instantiated by using the new keyword. We can create an empty collection and then add the model objects to it later or we can pass a few model objects in the collection while creating it.
// Lets create an empty collection var collection1 = new BooksCollection(); //Lets create a pre-populated collection var book1 = new Book({ ID: 1, BookName: "Book 1" }); var book2 = new Book({ ID: 2, BookName: "Book 2" }); var collection2 = new BooksCollection([book1, book2]);
Adding models to collection
To add an item to a collection, we can use the add method on the collection. The important thing to notice here is that if the item with the same id exist in the collection, the add will simply be ignored.
var book3 = new Book({ ID: 3, BookName: "Book 3" }); collection2.add(book3);
Now there might be a scenario where we actually want to update an existing added model in a collection. If that is the case, then we need to pass the {merge: true} option in the add function.
var book3 = new Book({ ID: 3, BookName: "Book 3" }); collection2.add(book3); var book3_changed = new Book({ ID: 3, BookName: "Changed Model" }); collection2.add(book3_changed, { merge: true });
Another important point to consider here is that the collection keep a shallow copy of the actual models. So if we change a model attribute after adding it to a collection, the attribute value will also get changed inside the collection.
Also, if we want to add multiple models, we can do that by passing the model array in the add method.
var book4 = new Book({ ID: 4, BookName: "Book 4" }); var book5 = new Book({ ID: 5, BookName: "Book 5" }); collection2.add([book4, book5]);
It is also possible to add the model at a specific index in the collection. To do this we need to pass the {at: location} in the add options.
var book0 = new Book({ ID: 0, BookName: "Book 0" }); collection2.add(book0, {at:0});
Note: push and unshift function can also be used to add models to collection.
Removing models from collection
To remove the model from the collection, we just need to call the remove method on the collection. The remove method simply removes this model from the collection.
collection2.remove(book0);
Also, if we want to empty the model, we can call the reset method on the collection.
collection1.reset();
It is also possible to reset a collection and populate it with new models by passing an array of models in the reset function.
collection2.reset([book4, book5]); // this will reset the collection and add book4 and book5 into it
Note: pop and shift function can also be used to remove model from collection.
Finding the number of items in collection
The total number of items in a collection can be found using the length property.
var collection2 = new BooksCollection([book1, book2]); console.log(collection2.length); // prints 2
Retrieving models from collection
To retrieve a model from a specific location, we can use the at function by passing a 0 based index.
var bookRecieved = collection2.at(3);
Alternatively, to get the index of a known model in the collection, we can use the indexOf method.
var index = collection2.indexOf(bookRecieved);
We can also retreive a model from a collection if we know its id or cid. this can be done by using the get function.
var bookFetchedbyId = collection2.get(2); // get the book with ID=2 var bookFetchedbyCid = collection2.get("c3"); // get the book with cid=c3
If we want to iterate through all the models in a collection, we can simply use the classic for loop or the each function provided by collections which is very similar to the foreach loop of underscore.js.
for (var i = 0; i < collection2.length; ++i) { console.log(collection2.at(i).get("BookName")); } collection2.each(function (item, index, all) { console.log(item.get("BookName")); });
Listening to collection events
Backbone collection raises events whenever an item is added removed to updated in the collection. We can subscribe to these events by listening to add, remove and change event respectively. Let us subscribe to these events in our model to see how this can be done.
var BooksCollection = Backbone.Collection.extend({ model: Book, initialize: function () { // This will be called when an item is added. pushed or unshifted this.on('add', function(model) { console.log('something got added'); }); // This will be called when an item is removed, popped or shifted this.on('remove', function(model) { console.log('something got removed'); }); // This will be called when an item is updated this.on('change', function(model) { console.log('something got changed'); }); }, });
The set function
The set function can be used to update all the items in a model. If we use set function, it will check for all the existing models and the models being passed in set. If any new model is found in the models being passed, it will be added. If some are not present in the new models list, they will be removed. If there are same models, they will be updated.
var collection3 = new BooksCollection(); collection3.add(book1); collection3.add(book2); collection3.add(book3); collection3.set([book1, { ID: 3, BookName: "test sort"}, book5]);
The above shown set function will call remove for book2, change for book3 and add for book5.
Sorting a collection
Backbone keeps all the models in the collection in a sorted order. We can call the sort function to forcefully sort it again but the models are always stored in sorted order. By default these items are sorted in the order they are added to the collection. But we can customize this sorting behavior by providing a simple comparator to our collection.
var BooksCollection = Backbone.Collection.extend({ model: Book, comparator: function (model) { return model.get("ID"); }, });
What this comparator does is that it overrides the default sorting behavior by specifying the attribute that should be used for sorting. We can even used a custom expression in this comparator too.
Fetch collection using HTTP REST service
To be able to fetch the collection from the server, we need to specify the url for the api that returns the collection.
var BooksCollection = Backbone.Collection.extend({ model: Book, url: "http://localhost:51377/api/Books", });
Now to fetch the collection from the server, lets call the fetch function.
var collection4 = new BooksCollection(); collection4.fetch();
Save collection using HTTP REST service
Lets see how we can save the items of a collection on the server.
var collection4 = new BooksCollection(); collection4.fetch({ success: function (collection4, response) { // fetch successful, lets iterate and update the values here collection4.each(function (item, index, all) { item.set("BookName", item.get("BookName") + "_updated"); // lets update all book names here item.save(); }); } });
In the above code we are calling save on each model object. this can be improved by either overriding the sync function on a collection or perhaps creating a wrapper model for collection and saving the data using that.
Note: The web api code for can be downloaded from the previous article of the series.
Point of interest
In this article we have discusses about the backbone collections. This has been written from a beginner’s perspective. I hope this has been informative.
原文链接:http://rahulrajatsingh.com/2014/07/backbone-tutorial-part-5-understanding-backbone-js-collections/
- backboneSample1.zip (127.4 KB)
- 下载次数: 0
发表评论
-
Part 8: Understanding Backbone.js Events
2016-06-22 10:34 824In this article, we will look a ... -
Part 7: Understanding Backbone.js Routes and History
2016-06-22 09:52 552In this article, we will try to ... -
Part 6: Understanding Backbone.js Views
2016-06-22 09:50 715In this article, we will try to ... -
Part 4: CRUD Operations on BackboneJs Models using HTTP REST Service
2016-06-21 14:21 891In this article we will discuss ... -
Part 3: More about Backbone Models
2016-06-21 14:08 747In this article we will look at ... -
Part 2: Understanding the basics of Backbone Models
2016-06-21 12:55 642When we talk about any MV* patt ... -
Part 1: Introduction to Backbone.Js
2016-06-21 11:12 719It was a long time ago (almost ...
相关推荐
Backbone.js 是一个轻量级的JavaScript库,它为Web应用提供了模型-视图-控制器(MVC)架构模式。在"TODO-APP: 使用Backbone.js开发ud989的项目"中,我们将深入探讨如何利用Backbone.js构建一个待办事项应用。 **一...
Backbone.js是一个JavaScript库,它提供了模型-视图-控制器(MVC)架构模式,帮助开发者组织代码,使得前端开发更加有序和高效。它强调数据模型和视图的绑定,以及事件驱动的编程方式。 Singool.js框架在其基础上...
Backbone.js是一款轻量级的JavaScript库,专为构建丰富的Web应用程序而设计。它通过提供模型(Models)、视图(Views)、集合(Collections)和路由器(Routers)等核心概念,帮助开发者组织代码并实现MVC(Model-...
Backbone.js 是一个轻量级的JavaScript库,主要用于构建可维护性和结构化的Web应用。它提供了一套模型-视图-控制器(MVC)架构,帮助开发者组织代码,使得前端开发更加有序。在深入探讨Backbone.js的开发秘笈源码...
backbone.js提供了一套web开发的框架,为复杂javascript应用程序提供一个mvc结构。, 《backbone.js应用程序开发》详细介绍了如何使用backbone.js完成web应用开发。全书从了解mvc、spa和backbone.js的基本知识开始,...
backbone.js提供了一套web开发的框架,为复杂javascript应用程序提供一个mvc结构。 《backbone.js应用程序开发》详细介绍了如何使用backbone.js完成web应用开发。全书从了解mvc、spa和backbone.js的基本知识开始,...
5. **测试**:由于Backbone.js应用通常包含大量的JavaScript代码,使用测试工具如Jasmine或Mocha进行单元测试和集成测试至关重要。 **文件名称分析** "Developing Backbone.js Applications -.htm"和"Developing ...
Backbone.js是一款轻量级的JavaScript库,专为构建复杂的Web应用而设计。它通过提供模型、视图、集合和路由器等概念,帮助开发者更好地组织和管理代码,实现MVC(Model-View-Controller)模式在前端的落地。陶国荣的...
Backbone.js是一款轻量级的JavaScript库,专为构建可维护性和结构化的Web应用而设计。它主要关注数据模型的管理、视图的渲染以及URL路由,为前端开发提供了强大的框架支持。本资源是关于"Backbone.js实战"的电子书,...
Backbone.js是一个轻量级的JavaScript库,专为构建可维护和模块化的Web应用而设计。它基于MVC(Model-View-Controller)模式,帮助开发者组织和管理前端代码结构,使得复杂的应用程序更容易理解和扩展。在“Backbone...
1. **Backbone.js框架**:Backbone.js是一个轻量级的JavaScript库,它为构建单页应用(SPA)提供了模型-视图-视图模型(MVVM)的架构模式,帮助开发者组织代码结构。 2. **Backbone.Radio**:Backbone.Radio是...
Pro Single Page Application Development - Using Backbone.Js and ASP.Net by Gil Fink and Ido Flatow.2014
Backbone.js提供了一套Web开发的框架,为复杂的JavaScript应用程序提供了一个MVC结构。 《Backbone.js应用程序开发》详细介绍了如何使用Backbone.js完成Web应用开发。全书从了解MVC、SPA和Backbone.js的基本知识...
Backbone.js是一个轻量级的JavaScript库,专为构建可维护和组织良好的前端应用程序而设计。这个库的核心理念是提供模型-视图-控制器(MVC)架构模式,帮助开发者在浏览器端更好地组织代码,提高代码复用性和可扩展性...
Backbone.js是一款轻量级的JavaScript库,专为构建可维护性和结构化的Web应用程序而设计。它主要关注数据模型的管理、视图的渲染以及事件处理,为前端开发者提供了一套MVC(Model-View-Controller)架构模式的实现。...
backbone.js提供了一套web开发的框架,为复杂javascript应用程序提供一个mvc结构。, 《backbone.js应用程序开发》详细介绍了如何使用backbone.js完成web应用开发。全书从了解mvc、spa和backbone.js的基本知识开始,...