<!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
.
方法 #1 会触发EventModel.initialize()
,而方法 #2 不会。
文档说可以像方法 #2 一样添加对象,那么,为什么我不像我那样构造对象new EventModel()
呢?引用文档:
如果定义了模型属性,您还可以传递原始属性对象,并将它们作为模型的实例进行激活。