主干:无法重写构造函数



我正试图用自己的构造函数覆盖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:操作数obj中的"in"无效这是我的套餐:

<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>

谢谢!

有两件事需要纠正:

  1. 如前所述,首选initialize而非constructor

  2. 遵循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"
});

您不需要覆盖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;
}   
});

最新更新