2012-09-03 28 views
0

下面簡單的代碼來尋找「身份證」拋出一個錯誤:Backbone.js的遺漏的類型錯誤:無法使用「在」運營商

"Uncaught TypeError: Cannot use 'in' operator to search for 'id' in Leo" in backbone-min.js:9

http://jsfiddle.net/nW7KF/

<!DOCTYPE html> 
<html> 
<head> 
<title></title> 
</head> 
<body> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> 
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script> 
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script> 
<script> 
var User = Backbone.Model.extend({ 
    initialize: function(n) { 
     this.name = n; 
    } 
}); 

var user = new User("Leo"); 
</script> 
</body> 
</html>​ 

我怎樣才能讓這個代碼與Backbone.js一起工作?

回答

3

您沒有正確構建模型。從Backbone.js的documentation

When creating an instance of a model, you can pass in the initial values of the attributes, which will be set on the model. If you define an initialize function, it will be invoked when the model is created.

new Book({ 
    title: "One Thousand and One Nights", 
    author: "Scheherazade" 
}); 

所以,你會構建模型是這樣的:http://jsfiddle.net/nW7KF/2/

<script> 
    var User = Backbone.Model.extend({}); 
    var leo = new User({ name: "Leo" }); 
    console.log(leo.get("name")); 
</script> 
+0

謝謝。有什麼方法可以在模型定義中定義模型的結構(用戶有'名稱'),而不是在實例化過程中? – tucson

+0

不要_define_ no,但可以重寫[Model.validate()](http://documentcloud.github.com/backbone/#Model-validate),或使用插件在模型上強制實施模式。 –

+0

@tucson:還有['Model.defaults'](http://backbonejs.org/#Model-defaults)來幫助解決這類問題。 –

3

我碰到了同樣的錯誤就在幾天前,這個問題竟然是那我使用的是更新版本的Backbone(1.2.1),它顯然實例化了與以前不同的模型。我一直在使用該庫的1.1.1版本,但是當我更新到1.2.1時,我開始看到同樣的錯誤。當我回到1.1.1時,錯誤不再發生。如果您看到相同的錯誤並進行相同的庫更新,可能需要注意。

+0

我有同樣的問題。 –

+0

我有同樣的問題。請給我一個解決方案。 –

0

您鏈接的文件已過期。請更新它們。

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
<script type="text/javascript" src="https://ajax.cdnjs.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"></script> 
<script type="text/javascript" src="https://ajax.cdnjs.com/ajax/libs/backbone.js/1.2.1/backbone-min.js"></script> 
相關問題