2014-10-08 74 views
0

我想重写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") 

以下错误,当出现: 类型错误:无效的 '在' 操作数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

'Backbone.Model.apply(this,arguments)'无效。你必须使用Backbone.Model'构造函数的原型' – hindmost 2014-10-08 20:43:26

+0

BTW:为什么你不使用'initialize'方法?它允许传递/接收参数 – hindmost 2014-10-08 20:45:50

+0

我该怎么做? – 2014-10-08 20:45:52

回答

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

}); 
+0

它仍然使相同的错误 – 2014-10-08 22:26:59

2

你有两件事情来纠正:

  1. 正如前面提到的,喜欢initialize超过constructor

  2. 按照API的new Model(attributes, options)。原因是骨干将采取你的第一个参数,并视为属性哈希值。如果它不是一个对象,它可能会有意想不到的行为。在这种情况下,你可能会碰到这样的:

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" 
}); 
+0

非常感谢你。我想实现某种多态,我想从Video继承,然后,子类只会获得URL,现在它将从URL中获取并解析所有其他字段。 – 2014-10-08 22:26:14