1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script
src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
</head>
<body>
<button id="cmd_create_event" name="cmd_create_event" type="button">Create
a new `Event`</button>
<script type="text/javascript">
var EventModel = Backbone.Model.extend({
initialize : function() {
console.log("`Event` is initialized. id: " + this.cid);
this.bind("change:status", function() {
console.log(this.get("status") + " is now the value for `status`");
});
this.bind("error", function(model, error) {
console.error(error);
});
},
defaults : {
"status" : 0
},
validate : function(attrs) {
if (attrs.status <= 0)
return "invalid status";
}
});
var EventList = Backbone.Collection.extend({
initialize : function() {
console.log("`EventList` is initialized");
},
model : EventModel,
add : function(event) {
console.log("`Event` added to `EventList`.");
}
});
var EventView = Backbone.View.extend({});
$(document).ready(function() {
var event_list = new EventList();
$("#cmd_create_event").click(function() {
// GENERATION METHOD #1:
/*var event = new EventModel();
event.set({
status : 1
});
event_list.add(event);*/
// GENERATION METHOD #2:
event_list.add({
status : 1
});
});
});
</script>
</body>
</html>
在上面的代碼有兩種方法我使用到EventModel
添加到EventList
。Backbone.js的Collection.add()不`construct`(`initialize`)的對象
方法#1發生火災EventModel.initialize()
,而方法#2沒有發生。
docs says有可能像方法#2那樣添加一個對象,那麼,爲什麼我沒有得到構建的對象,就好像我會new EventModel()
?引用文檔:
如果模型屬性定義,您也可以傳遞原始屬性 對象,讓他們來vivified作爲模型的實例。
我希望它知道這是我的意圖,而不必顯式調用超級'add()'。再次,我喜歡OOP!謝謝:) – Poni 2012-07-07 15:26:24
好吧,那麼你將無法覆蓋'add()' - 如果你想在添加到集合時做額外的事情,考慮綁定到集合的'add'事件。 – 2012-07-07 15:28:02
對,但現在我想到了 - 我只是簡單地忽略了這個功能,這不是我的意圖!我會簡單地將它綁定()到它。再次感謝你的小小澄清。 – Poni 2012-07-07 15:30:09