0

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 を作成せずに、これを修正するよりエレガントな方法はありますか。

4

1 に答える 1

2

これらの余分なプロパティをすべて取得する理由は、モデルをモデルとして渡すのではなく、コンストラクターに直接渡すためです。バックボーンはモデルの属性を読み取り、それらを html 属性としてビューに追加します。

通常、このようにモデルを渡します (バックボーンのドキュメントから直接)

var doc = Documents.first();

new DocumentRow({
  model: doc,
  id: "document-row-" + doc.id
});

このjsFiddleを見てください。モデルを使用するようにビューを少し作り直したところ、余分な html 属性なしでレンダリングされるようになりました。

于 2012-04-21T00:35:20.060 に答える