-2

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

Darshan
  • 3
  • 2
  • 1
    Why do you think it is not possible..? What did you try..? What exactly do you mean by *"i need to change these models in one of the view"* ..? Please don't consider stackoverflow as the place where you come and ask for code and people does your work for you. – T J Dec 10 '15 at 10:39

2 Answers2

1

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/

MorKadosh
  • 5,846
  • 3
  • 25
  • 37
  • One thing to note about this solution is that it would only work if the two models were instances of the same model class (or so I believe). But the title of the question says 'two independent models' which makes me think they may be different classes of model. – Xoundboy Dec 10 '15 at 12:40
0
var app = app||{};

app.Model1 = Backbone.Model.extend({
   //some code
});
app.Model2 = Backbone.Model.extend({
   //some code
});
var model1 = app.Model1();
var model2 = app.Model2();

app.View = Backbone.View.extend({
   initialize : function(options){
   console.log(options.model1);
   console.log(options.model2);
   }
});

var view = new app.View({model1 : model1, model2 : model2});

Thus, you can have binding with multiple models, and define appropriate functions to update the models individually.

Another very cool way to do this would be to use dynamic models as presented here: Backbone.js: complex views combining multiple models

Community
  • 1
  • 1
xssChauhan
  • 2,728
  • 2
  • 25
  • 36