问题描述
我有这样的code:
var MyModel = Backbone.Model.extend();
var MyCollection = Backbone.Collection.extend({
url: '/url/',
model: MyModel
});
var coll = new MyCollection();
URL是正确的,并返回正确的JSON。但是,如果我尝试使用下一个code:
The url is correct and returns correct json. But if I try to use the next code:
$('#fetch').click(function(){
coll.fetch();
console.log(coll.toJSON());
});
- 它显示我的数据只有第二次点击后(HTTP响应在Firebug后的第一个我看到)。似乎数据没有及时刷新。
如果我把每个语句在不同情况下它的工作原理是正确的。但我需要立即知道采集的长度。如何做到这一点?
If I put each statement in different event it works correct. But I need to know the length of collection immediately. How to do this?
推荐答案
请记住,取
是对服务器的异步调用。为了使您的code的工作如你所料,创建一个成功
函数 Backbone.Collection
可一旦调用从服务器刷新其内容:
Keep in mind that fetch
is an asynchronous call to the server. To make your code work as you expected, create a success
function that Backbone.Collection
can call once it refreshes its contents from the server:
$('#fetch').click(function(){
coll.fetch({
succcess: function() {
console.log(coll.toJSON());
}
});
});
显然,你的应用程序并不需要真的叫的console.log
这样一个更真实的例子会用骨干事件这样的绑定:
Obviously you app doesn't need to really call console.log
so a more real world example would use backbone's event binding like this:
coll.bind('refresh', someFunction);
coll.fetch();
通过这种方法,骨干将调用集合时刷新 someFunction
。这是非常有用的尤其是当 someFunction
是渲染
您要到您的收藏绑定该视图的功能。
With this approach, backbone will call someFunction
when the collection refreshes. This is really useful especially when someFunction
is the render
function of a view to which you want to bind your collection.
coll.bind('refresh', yourView.render);
coll.fetch();
这篇关于Backbone.js的获取问题(不能立刻刷新数据)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!