我有一个Backbone应用程序,我从后端API获取BackBone View中的数据,然后调用函数render
以使用我获得的数据呈现模板。
我想知道哪一个是获取和渲染的最佳实践,为什么?
1-使用提取,然后在render
上致电success
:
define(
['models/object',
'text!templates/home.html',
'backbone'
],
function(ObjectModel, HomeTemplate, Backbone) {
var homeView = Backbone.View.extend({
initialize: function(options) {
var self = this;
this.homeTemplate = _.template(HomeTemplate);
this.object = new ObjectModel({
id: <ANY_ID>
});
this.object.fetch({
success: function() {
self.render(self.object);
}
});
},
render: function(data) {
this.$el.html(this.homeTemplate);
console.log(data);
return this;
},
});
return homeView;
});
2-当objects
更改为render
后绑定:
define(
['models/object',
'text!templates/home.html',
'backbone'
],
function(ObjectModel, HomeTemplate, Backbone) {
var homeView = Backbone.View.extend({
initialize: function(options) {
var self = this;
this.homeTemplate = _.template(HomeTemplate);
this.object = new ObjectModel({
id: <ANY_ID>
});
this.object.bind('change', this.render, this);
this.object.fetch()
},
render: function(data) {
this.$el.html(this.homeTemplate);
console.log(data);
return this;
},
});
return homeView;
});