javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -
<!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 new `event`</button> <script type="text/javascript"> var eventmodel = backbone.model.extend({ initialize : function() { console.log("`event` initialized. id: " + this.cid); this.bind("change:status", function() { console.log(this.get("status") + " value `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` initialized"); }, model : eventmodel, add : function(event) { console.log("`event` added `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>
in above code there 2 methods i'm using add eventmodel
eventlist
.
method #1 fire eventmodel.initialize()
, while method #2 not.
the docs says it's possible add object method #2, so, why don't object constructed if new eventmodel()
? quoting docs:
if model property defined, may pass raw attributes objects, , have them vivified instances of model.
with first method, call constructor of model
var event = new eventmodel();
with second method, pass { status: 1 }
eventlist.add
method defined earlier, logs console , doesn't anything.
if call
backbone.collection.prototype.add.call(this, event);
in eventlist.add
method, backbone creates new model instance passed data , initialize()
called (because specified model
attribute when defining eventlist
).
Comments
Post a Comment