我试图用自己的方法覆盖Backbone.Model构造函数,以便能够从外部传递我的参数而不是创建对象。
这是我的代码:
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);
}
});
试图进入时
new Video("www.yahoo","coins.jpg","Yahoo",4,"hhhh","5stars.png")
出现以下错误: TypeError:无效' in'操作数obj 这是我的包括:
<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>
谢谢!
答案 0 :(得分:2)
您需要纠正两件事:
如前所述,首选initialize
而不是constructor
遵循new Model(attributes, options)
的API。原因是骨干将采用您的第一个参数,并将其视为属性哈希。如果它不是一个对象,它可能有意想不到的行为。在这种情况下,您可能会遇到以下情况:
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"
});
一个问题是:为什么要将这些参数作为第一类参数分配给模型对象,而不是作为模型属性?在这种情况下,您不需要添加构造函数,只需传递数据:
new Video({
videoUrl:"www.yahoo",
imageSource: "coins.jpg",
title: "Yahoo",
rating: 4,
description: "hhhh",
starsImageSource: "5stars.png"
});
答案 1 :(得分:1)
您不需要覆盖constructor
。
以下代码与您需要的完全相同:
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;
}
});