javascript - Backbone.js fetch collection from it's initialize method -
someone building app us, provided me code go through it, , noticed this, @ first seems ok, , nice let collection manage data after while started thinking possible pitfalls in idea
so: practice fetch collection's data it's own initialize method.
for example:
var book = backbone.model.extend({}); var books = backbone.collection.extend({ url: '/books', initialize: function(){ // logic here // if collection empty, fetch server if(this.size() == 0) this.fetch(); } });
i ask because feel might problem in following situation:
suppose in routeaction:
books: function() { var books = new books(); var booklist = new booklist({ collection: books }); }
isn't situation possible failure, if fetch faster initialization of view, view have bound reset event, reset have triggered way before initialize of view had been executed?
am wrong on this, or should submit ticket fixed.
while in practice initialization of view occur before fetch()
complete (and bind render()
reset
not initialize()
) it's bad idea rely on order of async operations anyway. in other words, code should written in way makes order irrelevant.
i have seen fetch()
being called in initialize()
in various projects. still think it's undesirable , bad practice. explicitly fetching when need has these advantages:
- you can when need to, not every time create new collection.
you can things in order if want to:
for example, can initialize view , render once have fetched.
var booklist, books = new books(); var p = books.fetch(); p.done(function () { booklist = new booklist({collection: books }); booklist.render(); });
it makes testing easier.
Comments
Post a Comment