2014-10-08 73 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