【发布时间】:2012-02-12 16:40:29
【问题描述】:
我正在尝试了解backbone.js 的一部分是如何工作的。应用程序启动后,我必须获取模型集合。我需要等到 fetch 完成才能呈现每个视图。 我不能 100% 确定在这种情况下采取的最佳方法。
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);
}
});
【问题讨论】:
-
你知道你提前得到了多少对象吗?为什么要等到它们全部关闭后再渲染。你能不能把页面设计成允许每个对象呈现自己并将其附加到 Dom 上?
-
当我尝试运行 this.customers.at(2) 并抓取第二个对象时,它总是返回未定义,除非我等到获取成功触发。我假设,这是我做错了并且没有完全理解的事情。我对 JScript 很陌生。
-
仅供参考。它是 JavaScript 而不是 jscript。 Jscript 是微软的混蛋子变种。但是是的,fetch 是非阻塞的,这意味着如果你调用 fetch,无论 fetch 的结果如何,下一个命令都会运行。看看我下面的答案。
标签: javascript asynchronous backbone.js