Backbone.js calling render after collection is pop

2019-03-03 21:47发布

I'm trying to call render after fetch of a collection.

In my initialize method I have:

this.collection.bind('all', this.render, this);
this.collection.fetch();

In IE it seems that sometimes it tries to render, before the collection has data. Collections don't seem to have a 'change' event that can be bound to, is there a better way to ensure that the collection has been fetched before rendering?

Thanks!

EDIT:

If I refresh the page, it seems to always work, however if I click in the address bar again and the page loads, it doesn't ever work.

4条回答
虎瘦雄心在
2楼-- · 2019-03-03 22:20

The following should definitely work, it worked for me...

instead of the below

this.collection.fetch();

use this

this.collection.fetch(async: false);
查看更多
Evening l夕情丶
3楼-- · 2019-03-03 22:24

Looking at Backbone's Catalog of Events sounds like you want to listen to the reset event

查看更多
倾城 Initia
4楼-- · 2019-03-03 22:31

If you want to guarantee that data has been fetched before rendering it, then I'd suggest using jQuery's deferred object:

this.collection.deferred = this.collection.fetch();
self = this;
this.collection.deferred.done(function() {
    self.collection.render();
  }
);

Basically anything you put into the function you send to done will only be called after fetch is, well, done.

More on deferreds:

查看更多
爷、活的狠高调
5楼-- · 2019-03-03 22:32

The following should work:

this.collection.on('reset', this.render);
this.collection.fetch();

Normally in Backbone.js one would use on() to bind a callback to an object.

查看更多
登录 后发表回答