我对使用backbone.js模型获取方法感到非常困惑。请参阅以下示例
主干路由器:
profile: function(id) {
var model = new Account({id:id});
console.log("<---------profile router-------->");
this.changeView(new ProfileView({model:model}));
model.fetch();
}
第一步,将实例化模型帐户,帐户模型如下所示。
define(['models/StatusCollection'], function(StatusCollection) {
var Account = Backbone.Model.extend({
urlRoot: '/accounts',
initialize: function() {
this.status = new StatusCollection();
this.status.url = '/accounts/' + this.id + '/status';
this.activity = new StatusCollection();
this.activity.url = '/accounts/' + this.id + '/activity';
}
});
return Account;
});
urlRoot属性是用于什么的?创建模型对象后,将使用该模型模型(this.changeView({ profileview :ProfileView}));呈现ProfileView,changeview函数如下所示。
changeView: function(view) {
if ( null != this.currentView ) {
this.currentView.undelegateEvents();
}
this.currentView = view;
this.currentView.render();
},
渲染视图后,profile信息还不会显示,但执行model.fetch();语句后,会显示模型中的数据,这是为什么?我真的不知道fetch是如何工作的,我试图找出答案,但没有机会。
发布于 2013-05-14 22:49:40
我不完全确定你的问题是什么,但我会尽我所能解释。
urlRoot背后的概念是基URL,子元素将被获取到它下面,并将id添加到该urlRoot中。
例如,以下代码:
var Account = Backbone.Model.extend({
urlRoot: '/accounts'
});
将设置基本url。然后,如果您要实例化它并调用fetch():
var anAccount = new Account({id: 'abcd1234'});
anAccount.fetch();
它将发出以下请求:
GET /accounts/abcd1234
在这里,您设置了urlRoot,然后显式地设置了一个urlRoot,这样您提供的url将被忽略。
我鼓励您查看主干源代码(令人惊讶地简洁),以了解url是如何派生的:http://backbonejs.org/docs/backbone.html#section-65
为了回答您的另一个问题,您的配置文件信息不会立即显示的原因是,fetch()连接到网络,转到您的服务器,并且必须等待回复才能显示。
这不是即时的。
它是以非阻塞的方式完成的,这意味着它将发出请求,继续做它正在做的事情,当请求从服务器返回时,它会触发一个事件,Backbone使用该事件来确保现在有了模型的数据,必须做的任何其他事情都完成了。
我在您的代码片段中添加了一些注释来解释这里发生的事情:
profile: function(id) {
// You are instantiating a model, giving it the id passed to it as an argument
var model = new Account({id:id});
console.log("<---------profile router-------->");
// You are instantiating a new view with a fresh model, but its data has
// not yet been fetched so the view will not display properly
this.changeView(new ProfileView({model:model}));
// You are fetching the data here. It will be a little while while the request goes
// from your browser, over the network, hits the server, gets the response. After
// getting the response, this will fire a 'sync' event which your view can use to
// re-render now that your model has its data.
model.fetch();
}
因此,如果你想确保你的视图在模型被获取后被更新,你有几种方法可以做到:(1)传递一个成功的回调给model.fetch() (2)在你的视图监视器上注册一个处理程序用于“同步”事件,当它返回时重新呈现视图(3)将实例化你的视图的代码放在一个成功的回调中,这样直到网络请求返回并且你的模型有了它的数据之后视图才会被创建。
https://stackoverflow.com/questions/16544984
复制相似问题