Backbone.js in the collection of details _ other

Source: Internet
Author: User
Tags bind extend

The set of Backbone.js is simply a model of a simple ordered set. By adapting models and collections, we can avoid the logic of data processing in our view layer. In addition, models and collections provide a convenient way to work with the backend, and can automatically mark the Backbone.js view when data changes. In this way, it can be used in the following situations:

Copy Code code as follows:

Model:animal, Collection:zoo

Usually your set fits only one model, but the model itself is not limited to the type of collection.
Copy Code code as follows:

Model:person, Collection:office
Model:person, Collection:home

The following are examples of common models/collections:
Copy Code code as follows:

var Music = Backbone.Model.extend ({
Initialize:function () {
Console.log ("Welcome to the Music world");
}
});
var Album = Backbone.Collection.extend ({
Model:music
});

The code above tells us how to create a collection. But it does not tell us the process of manipulating the collection with data. So let's explore this process:

Copy Code code as follows:

var Music = Backbone.Model.extend ({
Defaults: {
Name: "Not Specified",
Artist: "Not Specified"
},
Initialize:function () {
Console.log ("Welcome to the Music world"); }
});
var Album = Backbone.Collection.extend ({
Model:music
});
var music1 = new Music ({id:1, Name: "How Bizarre", Artist: "OMC"});
var music 2 = new Music ({id:2, Name: "What hurts the Most", Artist: "Rascal Flatts"});
var myalbum = new Album ([Music 1, Music 2]);
Console.log (Myalbum.models);

Let's look at the relationship between the Backbone.js collection and other components:

Add a model to a collection

As we know, a collection is a collection of models. Therefore, we can add the model to the collection. To add a model to a collection, we can use the Add method. We can also add models to the beginning of the collection-by using the Unshift method.

Copy Code code as follows:

var music3 = new Music ({id:3, Name: "Yes I do", Artist: "Rascal Flatts"});
Music.add (MUSIC3);
Console.log (' New Song Added ');
Console.log (Json.stringify (Music));

Ii. removing models from the collection

Many times, we have the need to remove some of the specified data from the collection. To remove the model from the collection, we need to provide the ID of the model. If we want to replace the original set with a complete new dataset, we can use the Reset method.

Copy Code code as follows:

Music.remove (1);
Console.log (' How bizarre removed ... ');
Console.log (Json.stringify (Music));

III, GET and set

If we need to get a value from a collection somewhere else in the code, we can use the Getting method directly. At this point, we pass the ID value to the model with the retrieval.

Copy Code code as follows:

Console.log (Json.stringify (Music.get (2)));

The set method of the set has an interesting implementation. The Set method performs a "smart" update of the collection by passing the list of models. If the model in the list is not yet in the collection, it is added to the collection. If the model is already in the collection, its properties are merged. If the collection contains any models that are not part of the list, the model is removed.
Copy Code code as follows:

var Music = Backbone.Model.extend ({
This attribute should is set as a default
Defaults: {
Name: '
},
Set the id attribute so the collection
Idattribute: ' ID '
});
var song = Backbone.Collection.extend ({
Model:music
});
var models = [{
Name: ' OMC ',
Id:1
}, {
Name: ' Flatts ',
Id:2
}];
var collection = new song (models);
Collection.bind (' Add ', function (model) {
Alert (' Addb ')
});
Collection.bind (' Remove ', function () {
Alert (' Add ')
});
Models = [{
Name: ' OMC ',
Id:1
}, {
Name: ' Flatts ',
Id:2
}, {
Name: ' Jackson ',
Id:3
}];
Collection.add (models);
});

As we have seen above, we already have 2 models beforehand, and when we add the 3rd model, the previous model remains unchanged.

Four, constructors and initialization

When we create a collection, we can pass the initialization array of the model. The comparer for the collection can be added as an option. If the comparator option passed is false, the sort is blocked. If we define an initialization function, this function is invoked when the collection is created. Several options are described below, which, if provided, are added directly to the collection: the model and the comparer.

Copy Code code as follows:

var tabs = new Tabset ([Tab1, TAB2, Tab3]);
var spaces = new Backbone.collection ([], {
Model:space
});

Five, Tojson

The Tojso method returns an array containing the hash properties for each model in the collection. This method is often used to serialize and persist the collection as a whole.

Copy Code code as follows:

var song = new Backbone.collection ([
{name: ' Flatts '},
{name: ' OMC '},
{Name: "Jackson"}
]);
Alert (Json.stringify (song));

VI, Comparator comparator

By default, the collection is not with a comparer. If we define a comparer, it can be used to keep a set of sorts. This means that when you add a model, the model is inserted into the appropriate location in the collection. The comparer can be defined with SortBy or as a string to indicate the sorted property.

The SortBy comparer function gets a model and returns a number or string.

The sort comparer function gets two models, if the first model is preceded by the second model, then returns 1, and if two models are siblings, then returns 0; if the second model is preceded by the first model, then returns 1.

Let's take a look at the examples below:

Copy Code code as follows:

var student = Backbone.model;
var students = new Backbone.collection;
Students.comparator = ' name ';
Students.add (new Student ({name: "Name1", Roll:9}));
Students.add (new Student ({name: "Name2", Roll:5}));
Students.add (new Student ({name: "Name3", roll:1}));
Alert (Students.pluck (' roll '));

The collection of the comparer is not automatically reordered, even if we modify the properties of the model. So we should call sort when we modify the model properties and estimate that it will affect the sort.

Vii. sorting

When you add a model to a collection, you should force the collection to reorder. To disable sorting when the collection adds a model, you can pass the {sort:false} parameter. Calling a sort trigger checks this parameter.

Copy Code code as follows:

Sortbytype:function (type) {
This.sortkey = type;
This.sort ();
}

and view functions:
Copy Code code as follows:

Sortthingsbycolumn:function (event) {
var type = event.currenttarget.classlist[0]
This.collections.things.sortByType (Type)
This.render ()
}

Eight, picking

Pluck: Picking a property from each model in the collection is equivalent to calling the map from the iterator and returning a single property.

Copy Code code as follows:

var song = new Backbone.collection ([
{name: ' Flatts '},
{name: ' OMC '},
{Name: "Jackson"}
]);
var names = Songs.pluck ("name");
Alert (json.stringify (names));

Nine, Where

Where: Returns an array of all the models in the collection that match the passed properties, using a filter.

Copy Code code as follows:

var song = new Backbone.collection ([
{name: "Yes I do", Artist: "Flatts"},
{name: ' How Bizarre ', Artist: "How Bizarre"},
{Name: "What hurts the Most", Artist: "Flatts"},
]);
var artists = Song.where ({artist: "Flatts"});
alert (artists.length);

10, URL
Setting the URL property in the collection refers to the location of the server. The model within the collection uses this URL to construct its own URL.
Copy Code code as follows:

var songs = Backbone.Collection.extend ({
URL: '/songs '
});
var songs = Backbone.Collection.extend ({
Url:function () {
return This.document.url () + '/songs ';
}
});

11, analysis
Parse: invoked by backbone when fetching fetch, regardless of whether the server returns a model of the collection. This function passes the original response object, and he should return an array of the model properties that were added to the collection. The default implementation is the null operation No-op. Simply pass the JSON response, overwriting the operation with a pre-existing API, or better namespace response.
Copy Code code as follows:

var songs = Backbone.Collection.extend ({
Parse:function (response) {
return response.results;
}
});

12. Extract
Fetch: Extracts the default set of models from the server and sets them in the collection when they are retrieved. This option hashes to accept success or error callbacks, and he passes (sets, responses, options) three parameters. The model data is then returned from the server. It is used to set the model for merging extraction.
Copy Code code as follows:

Backbone.sync = function (method, model) {
Alert (method + ":" + Model.url);
};
var songs = new Backbone.collection;
Songs.url = '/songs ';
Songs.fetch ();

As you can see above, there are so many ways of simply backbone collections to improve the quality of your code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.