简体   繁体   中英

Backbone View receiving regular object instead of model

Here I am passing a model to a Backbone view.

 view = new View ({model:{item:4,name:"Ipad"}});

When I console.log that model from within the View. I get:

Object {item: 4, title: "Ipad"} 

This is not a backbone model therefore I don't have methods like toJSON. I realize that if I define a Backbone model and passed it in everything works fine.

view = new GenreView ({model:new Model({title: 4, title: "Ipad"})});

This logs

 r {cid: "c2", attributes: Object, _changing: false, _previousAttributes: Object, changed: Object…}

Why is it that first approach doesn't work and how can I fix it?

Its simply that the special 'model' option expects a Backbone.Model not a javascript object.

So you are correct when you create a new Backbone.Model to pass into the view.

There is nothing to fix as far as I can tell.

You need to use a Backbone.Model instead of a regular JavaScript object {}

var Item = Backbone.Model.extend({
  // ...
});

Instantiate the Item model

var myItem = new Item();

Now use your item in the view

var myView = new View({model: myItem});

This answer assumes that View is setup as something like

var View = Backbone.View.extends({
  // ...
});

You could cast the object to a Backbone Model in your view's initialize method:

var View = Backbone.View.extend({
  initialize: function(options){
    if (_.isPlainObject(this.model)) {
      this.model = new Backbone.Model(this.model);
    }
  }
});

This way the view will be able to operate on it's model regardless of whether you passed it an instance of a Backbone.Model or a plain object. You can see an example of it working here: http://jsbin.com/igecEgE/1/edit?js,console

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM