Part 5:Under standing Backbone.js Collection


もっと読む
In this article we will discuss abone.js collection s.We will see how we can use collection s to maniulate a group of models and how we can use retul API to easure fetch and save collection.
Background
Every appication need to create a collection of models which can be orded,iterated and perhaps sorted and searched when a need arseseseseseses.Keeping this mind,backbone also collection type which makers with a collection type
Link to compleete series:
  • Part 1:Introduction to Backbone.Js
  • Part 2:Understanding the baics 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 Collection
  • Part 6:Understanding Backbone.js View
  • Part 7:Understanding Backbone.js Routes and History
  • Part 8:Understanding Backbone.js Events
  • Using the code
    Let us start looking at the backbone collection s in details.
    Creating a collection
    Creating a backbone collection is simiar to creating a model.We just need to  exted the backbone’s collection clast to create our collection.Let us conting working with the same example where we created a  Book model and lets try to create a simple  Books Collection.
    var BooksCollection = Backbone.Collection.extend({
    });
    This collection will Hold the Book model we have created in our previous articales.
    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 shuld 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.The n all the operation on on on on on on on on this collection oject will the cleat the parturation
    Instantiating a collection
    A collection can be instantiated by using the  new keyword.We can create an empty collection and the n add the model object to it later or we can pass a few model object 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 importent 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 scenaro where we actually want to udate 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 impoint to consider here is that the collection keep a show copy of the actual models.So if we change a model after adding it to a collection,the atribute valute will alsogeot changer.control.inection.
    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});
    ノート:  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 empy the model,we can cal the  reet method on the collection.
     collection1.reset();
    It is also possible to reset a collection and poputlate it with new models by passing an array of models in the reet 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);
    Alternative ely,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  アイドル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 collection s which is very simillar to the foreach loop of undersscore.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ライヴevents whenever an item is added removed to udated in the collection.We can subscribe to these events by listening to  add、  remove and  change event respively.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  私は、If we set function、it will chek for all the exininingmodels and the models being passed in set.If any new model is found ininininininininininininininininininininininininindededededededededededededededededededededeststststste e e e e e e e e e e e e e e e padedededededededededededededededededededededededededededededededededededededededededededededededededededededededededededededededededededede私のmodels,they will be udated.
    
    var collection3 = new BooksCollection();
    collection3.add(book1);
    collection3.add(book2);
    collection3.add(book3);
    collection3.set([book1, { ID: 3, BookName: "test sort"}, book5]);
    The abook 3 and add for book 5.
    Sorting a collection
    Backbone keeps all the models in the collection in a sorted order.We can cal the  sort function to forcefully sort it again but the models are always stored in sorted order.By default thers items are sorted in the order the collection.But we can customi zed order.By proviction
    
    var BooksCollection = Backbone.Collection.extend({
        model: Book,
        
        comparator: function (model) {
            return model.get("ID");
        },
    });
    What this comprator does is that it overrides the default sorting bevior by specifying the atribute that shoud be used for sorting.We can even a custom expression in this coratoo.
    Fetch collection using HTTP REST service
    To be able to  fetch the collection from the server,we need to specify the  url for the apper returns the collection.
    
    var BooksCollection = Backbone.Collection.extend({
        model: Book,
     
        url: "http://localhost:51377/api/Books",
    });
    Now to  fetch the collection from the server,letscal 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 caling save on each model oject.this can be improved by eigthe overriding the sync function on a collection or perhaps creating a wrapper model for collection and saving the dausing that.
    Note:The webアプリcode for can be downloaded from the previous article of the series.
    Point of interest
    In this articale we have discusses abot the backbone collection.This has been written from a beginner's perspective.I hope this has been formative.
    原文のリンク:http://rahulrajatsingh.com/2014/07/backbone-tutorial-part-5-understanding-backbone-js-collections/
  • backboneSample 1.zip(127.4 KB)
  • ダウンロード回数:0