Fra*_*kie 49 javascript asynchronous backbone.js
我试图了解backbone.js的一部分是如何工作的.应用程序开始后,我必须获取一组模型.我需要等到fetch完成才能呈现每个视图.我不是百分百肯定在这个例子中采取的最佳方法.
var AppRouter = Backbone.Router.extend({
routes: {
"": "home",
"customer/:id": "customer"
},
home: function () {
console.log("Home");
},
customer: function (id) {
if (this.custromers == null)
this.init();
var customer = this.customers.at(2); //This is undefined until fetch is complete. Log always says undefined.
console.log(customer);
},
init: function () {
console.log("init");
this.customers = new CustomerCollection();
this.customers.fetch({
success: function () {
console.log("success");
// I need to be able to render view on success.
}
});
console.log(this.customers);
}
});
Run Code Online (Sandbox Code Playgroud)
Rov*_*ion 64
我使用的方法是jQuery完全回调,如下所示:
var self = this;
this.model.fetch().done(function(){
self.render();
});
Run Code Online (Sandbox Code Playgroud)
这是在Backbone 错误报告中推荐的.虽然bug报告建议使用complete,该回调方法已被弃用的青睐done.
小智 24
您也可以使用jquery 1.5+执行此操作
$.when(something1.fetch(), something2.fetch()...all your fetches).then(function() {
initialize your views here
});
Run Code Online (Sandbox Code Playgroud)
tko*_*one 10
您可以将自己的options.success发送到集合提取方法,该方法仅在提取完成时运行
来自骨干源(0.9.1中的起始线624)
fetch: function(options) {
options = options ? _.clone(options) : {};
if (options.parse === undefined) options.parse = true;
var collection = this;
var success = options.success;
options.success = function(resp, status, xhr) {
collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);
if (success) success(collection, resp);
};
Run Code Online (Sandbox Code Playgroud)
注意倒数第二行.如果您已将options对象中的函数作为success键传递,则在将集合解析为模型并将其添加到集合后,它将调用它.
所以,如果你这样做:
this.collection.fetch({success: this.do_something});
Run Code Online (Sandbox Code Playgroud)
(假设该initialize方法绑定this.do_something到this...),它将在整个shebang之后调用该方法,允许您在fetch/parse/attach之后立即触发操作
| 归档时间: |
|
| 查看次数: |
57482 次 |
| 最近记录: |