【发布时间】:2013-12-13 15:32:39
【问题描述】:
我会尽量简化这个..
我的 routes.js :
direct_message: function(member_id) {
list.conversations(function(conversations) {
conversation_view.model = conversations.models[conversations.models.length - 1];
conversation_view.render();
});
好的,conversations() 是我的列表模型中的一个函数,它有一个方便的小 fetch() 方法和一个回调(这是我传递给它的方法)。它检查是否已获取,如果是,则返回带有获取参数的回调。因此:
conversations: function(callback) {
var _callback = _.bind(function() { if(callback) callback(this._conversations); }, this);
if(!this._conversations) {
this._conversations = new app.collections.Conversations();
this._conversations.url = this._url();
app.events.on('pusher:conversation_started', this._conversation_started, this);
}
if(this._conversations._fetched) {
_callback();
} else {
this._conversations.on('reset', _callback);
if(!this._conversations._fetching) {
this._conversations._fetching = true;
this._conversations.fetch({
success: function(c) { c._fetched = true; },
error: function(c) { c._fetching = false; }
});
}
}
return this._conversations;
},
呸!我希望我还没有失去你。因此,这在一段时间内一切正常。但是现在,由于某种原因,当我在 routes.js 中执行该方法时,它返回为 undefined。
我认为发生这种情况的原因是该获取请求是异步的。所以返回正确返回,但在数据返回之前调用了return 语句。所以对conversation() 的所有其他调用实际上都正确返回,除了第一个初始化它的调用。
然后我在想,让我在 fetch() 调用中添加async: false,但是当我这样做时,由于某种原因,后来的调用会返回undefined。还有什么我可以做的吗?也许我应该看看别的东西?可能有什么方法可以在其中合并 $.deferred 对象?
非常感谢!
【问题讨论】:
标签: jquery backbone.js asynchronous fetch jquery-deferred