backbone.js アプリケーションをほぼ完成させましたが、アイテムのテーブルを表示するために選択した方法が正しい方法であるかどうか疑問に思っています。
いくつかのアイテムを表示するコードは次のとおりです。
var items = new Items();
items.fetch({
success: function(){
var itemsView = new ItemsView(items);
itemsView.$el.appendTo('#content-wrapper');
// Here I run some functions that
// remove all elements of the prev page
}
});
window.Item = Backbone.Model.extend({});
window.Items = Backbone.Collection.extend({
model: Items,
url: 'items'
});
window.ItemsView = Backbone.View.extend({
tagName: 'table',
id: 'items',
initialize: function(items) {
_.bindAll(this, 'render');
this.items = items;
this.items.bind('reset', this.render);
this.render();
},
render: function () {
var self = this;
this.items.each(function (item) {
self.addItem(item);
});
return this;
},
addItem: function(item) {
var itemView = new window.ItemView(item);
this.$el.append(itemView.el);
}
});
window.ItemView = Backbone.View.extend({
tagName: 'tr',
initialize: function (item) {
_.bindAll(this, 'render', 'serverChange');
this.item = item;
// Note that I am using Backbone.IO, it has a slightly
// different sync functions to support Socket.IO
this.item.ioBind('update', this.serverChange, this);
this.render();
},
serverChange: function(data){
this.item.set(data);
this.render();
},
render: function () {
this.$el.html(_.template('<td><%=name%></td>', this.item.toJSON()));
return this;
}
});
問題
私が直面している問題は次のとおりです。このコードによって生成される HTML は、非常に醜いものです。
モデルの変数ごとに HTML 属性を作成しました。次のようになります。
<table id="items">
<tr name="Awesome Product" id="75483920743829930" _id="75483920743829930" type="gel" price="200.00" stock="5">
<td>Awesome Product</td>
</tr>
</table>
これは私が望むものではありません。
私がこの方法を選んだ理由
すべてのアイテム ( tr
) には独自のビューがあるため、この方法を使用しました。したがって、1 つのモデルが変更された場合、テーブル全体を再レンダリングする必要はなく、1 つのビューだけを再レンダリングする必要があります。
面倒な HTML を作成せずに、これを修正するよりエレガントな方法はありますか。