Detailed explanation of the collection of Backbone. js (I)

Source: Internet
Author: User

Details on the collection of Backbone. js (I)

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

Model: Animal, Collection: Zoo

Generally, your set only adapts to one model, but the model itself is not limited to the set type.
Model: person, Collection: OfficeModel: person, Collection: Home

The following is an example of a common model/set:
var Music = Backbone.Model.extend({      initialize: function(){          console.log("Welcome to the music world");      }});var Album = Backbone.Collection.extend({    model: Music});

The code above shows how to create a set. However, it does not tell us how to manipulate a set with data. Therefore, let's explore this process:
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 take a look at the relationship between the collection of Backbone. js and other components:


1. Add a model to a set

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

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. Remove a model from the set

In many cases, we need to remove some specified data from the collection. To remove a model from a set, we need to provide the model id. If we want to replace the original set with a complete new dataset, we can use the reset method.

Music.remove(1);console.log('How Bizarre removed...');console.log(JSON.stringify(Music));

3. Get and Set

If we need to obtain a value from the collection in other parts of the code, we can directly use the get method. At this point, we pass the ID value to the model with the search.

console.log(JSON.stringify(Music.get(2)));

The set Method of a set has an interesting implementation. The set Method transmits the model list to perform the "smart" Update of the set. If the model in the list is not in the collection, it is added to the set. If the model is already in the Set, its attributes are merged. If the set contains any model that does not belong to the list, the model will be removed.
var Music = Backbone.Model.extend({         // This attribute should be set as a default        defaults: {            Name: ''        },        // Set the id attribute so that 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 two models. When we add 3rd models, the previous models remain unchanged.

Related Article

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.