我遇到了这篇文章(http://coenraets.org/blog/2012/01/backbone-js-lessons-learned-and-improved-sample-app/),并想知道在实例化它们之后绑定和渲染路由器视图是否是最佳实践。我一直约束我的观点,并将它们呈现在我的视图定义中。Backbonejs视图绑定概念反馈
目前,这是我如何被建立,并要求我的看法:
EmployeeView:
EmployeeView = Backbone.View.extend({
el: '#content',
template:template,
initialize: function() {
this.collection.fetch({
reset: true
});
this.collection.on('reset',this.render, this);
},
render: function(){
this.el.innerHTML = Mustache.to_html(this.template, { employee_list: this.collection.toJSON()});
console.log('render called');
}
我的路由器:
employeeList: function() {
var c = new EmployeeCollection
new EmployeeView({
collection: c
});
}
它工作正常。但根据文章更好的做法是做到以下几点:
EmployeeView = Backbone.View.extend({
template:template,
initialize: function() {
this.collection.fetch({
reset: true
});
this.collection.on('reset',this.render, this);
},
render: function(){
this.el.innerHTML = Mustache.to_html(this.template, { employee_list: this.collection.toJSON()});
console.log('render called');
return this;
}
路由器
employeeList: function() {
var c = new EmployeeCollection
$('#content').html(new EmployeeView({collection: c}).render().el);
},
我喜欢的文章中的解决方案,因为它能够消除其他DOM事件的观点作为文章说和允许我将所有调整和定制集中在一个地方,即路由器。但是因为我传入一个集合/模型,并且需要在初始化我的页面中获取数据两次。我的问题是:
- 这真的是最好的做法吗?
- 如果我想使用建议的方法,我该如何避免两次调用渲染?
- 如果我有一些情况,我有一些前端用户交互,然后需要刷新视图集合/模型会怎么样?我需要按照我的观点来做,还是可以在路由器中发生?