Search code examples
backbone.jsbackbone-views

Can 2 independent models be updated in one view in backbone.js


I have 2 seprate models an i need to change these models in one of the view.

Can this be done using backbone.js

If yes can anyone provide me a brief sample

Thanks


Solution

  • One way to do this is to bind a collection of these models to the view:

    var collection = new Backbone.Collection();
    collection.add(model1);
    collection.add(model2);
    

    And when you create the view, you should initialzie it with this collection:

    var myView = new View({collection:collection});

    Then, in the view you can change each of the views the following way:

      events :{ 'input input' : 'updateModels'},
      updateModels: function(e){
        for(var i=0;i<this.collection.length;i++)
        {
            this.collection.at(i).set({'someProperty':'someValue'});
        }
      }
    

    The above example will be fired for example when the user inputs.

    Another way is to set a custom property in your collection to hold an array of these models and then do the same thing, but I think that using collections could do the work for you.

    You can see a very simple and dummy example here: http://jsfiddle.net/nwo5bww1/