我遇到了這篇文章(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事件的觀點作爲文章說和允許我將所有調整和定製集中在一個地方,即路由器。但是因爲我傳入一個集合/模型,並且需要在初始化我的頁面中獲取數據兩次。我的問題是:
- 這真的是最好的做法嗎?
- 如果我想使用建議的方法,我該如何避免兩次調用渲染?
- 如果我有一些情況,我有一些前端用戶交互,然後需要刷新視圖集合/模型會怎麼樣?我需要按照我的觀點來做,還是可以在路由器中發生?