zer*_*ing 20 model backbone.js
我对使用backbone.js模型获取方法非常困惑.请参阅以下示例
骨干路由器:
profile: function(id) {
var model = new Account({id:id});
console.log("<---------profile router-------->");
this.changeView(new ProfileView({model:model}));
model.fetch();
}
Run Code Online (Sandbox Code Playgroud)
第一步,模型帐户将被实例化,帐户模型如下所示.
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;
});
Run Code Online (Sandbox Code Playgroud)
urlRoot属性是什么?创建模型对象后,将使用this.changeView(new ProfileView({model:model}))呈现profileview ; ,changeview函数看起来像这样.
changeView: function(view) {
if ( null != this.currentView ) {
this.currentView.undelegateEvents();
}
this.currentView = view;
this.currentView.render();
},
Run Code Online (Sandbox Code Playgroud)
在渲染视图之后,配置文件信息将不会显示,但是在model.fetch()之后; 语句执行,将显示模型中的数据,为什么?我真的不知道fetch如何工作,我试图找出,但没有机会.
Vic*_*inn 44
我不完全确定你的问题是什么,但我会尽力解释我的能力.
urlRoot背后的概念是基本URL,子元素将在其下面获取,并将id添加到该urlRoot.
例如,以下代码:
var Account = Backbone.Model.extend({
urlRoot: '/accounts'
});
Run Code Online (Sandbox Code Playgroud)
将设置基本网址.然后,如果你要实例化它并调用fetch():
var anAccount = new Account({id: 'abcd1234'});
anAccount.fetch();
Run Code Online (Sandbox Code Playgroud)
它会提出以下要求:
GET /accounts/abcd1234
Run Code Online (Sandbox Code Playgroud)
在您的情况下,您正在设置urlRoot,然后显式设置URL,以便忽略您提供的urlRoot.
我鼓励您查看Backbone源(这是令人惊讶的简洁),看看网址是如何派生的: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();
}
Run Code Online (Sandbox Code Playgroud)
因此,如果您希望确保在获取模型后更新视图,则有几种方法可以执行此操作:(1)将成功回调传递给model.fetch()(2)在视图上注册处理程序'sync'事件,在返回时重新呈现视图(3)将代码用于在成功回调中实例化视图,这样直到网络请求返回并且模型有其数据之后才会创建视图.
| 归档时间: |
|
| 查看次数: |
55692 次 |
| 最近记录: |