Reputation: 26486
I'm trying to override Backbone.Model constructor with my own, in order to be able to pass my parameters from outside and not as a created-object.
here is my code:
var Video = Backbone.Model.extend({
constructor : function (videoUrl,imageSource,title,rating,description,starsImageSource){
this.videoUrl = videoUrl;
this.imageSource = imageSource;
this.title = title;
this.rating = rating;
this.description = description;
this.starsImageSource = starsImageSource;
Backbone.Model.apply(this, arguments);
}
});
when trying to enter
new Video("www.yahoo","coins.jpg","Yahoo",4,"hhhh","5stars.png")
the following error appear: TypeError: invalid 'in' operand obj here is my includes:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js" type="text/javascript"></script>
<script src="http://marionettejs.com/downloads/backbone.marionette.js" type="text/javascript"></script>
thanks!
Upvotes: 0
Views: 244
Reputation: 3091
You have two things to correct:
As mentioned before, prefer initialize
over constructor
Follow the API of new Model(attributes, options)
. The reason is backbone will take your first argument and treat is as as an attributes hash. in case its not an object, it may have unexpected behavior. In this case you may have something like:
var Video = Backbone.Model.extend({
initialize : function (attrs, options){
_.extend(this, _.pick(options, 'videoUrl', 'imageSource', 'title', 'rating', 'description', 'starsImageSource'));
}
});
new Video(null, {
videoUrl:"www.yahoo",
imageSource: "coins.jpg",
title: "Yahoo",
rating: 4,
description: "hhhh",
starsImageSource: "5stars.png"
});
One question would be: why do you want to assign these parameters as first class parameters on the model object, and not as model attributes? In this case you don't need to add a constructor, just to pass the data:
new Video({
videoUrl:"www.yahoo",
imageSource: "coins.jpg",
title: "Yahoo",
rating: 4,
description: "hhhh",
starsImageSource: "5stars.png"
});
Upvotes: 2
Reputation: 7195
You don't need to override constructor
.
The following code does exactly the same you need:
var Video = Backbone.Model.extend({
initialize : function (videoUrl,imageSource,title,rating,description,starsImageSource){
this.videoUrl = videoUrl;
this.imageSource = imageSource;
this.title = title;
this.rating = rating;
this.description = description;
this.starsImageSource = starsImageSource;
}
});
Upvotes: 1