Reputation: 2165
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?
Upvotes: 1
Views: 68
Reputation: 17168
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
Upvotes: 1
Reputation: 77778
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({
// ...
});
Upvotes: 1
Reputation: 2952
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.
Upvotes: 2