6

モデルのビュー用に 2 つの異なるテンプレートがあります。モデルがデータベースからフェッチされるたびに、バックエンドからフェッチされた最初の 3 つのモデル (#1、2、3) には最初のテンプレートを使用して作成されたビューがあり、次の 4 つのモデル (#4、5、6、7) にはビューが作成されます。は 2 番目のテンプレートを使用し、次の 3 つのモデル (#8、9、10) は最初のテンプレートを使用するというように続きます。

問題: backbone.js を使用して、この代替テンプレートを導入するにはどうすればよいですか?

JS コード

// Views

PhotoListView = Backbone.View.extend({
    el: '#photo_list',

    render: function() {
        $(this.el).html('');
        _.each(this.model.models, function(photo) {
            $(this.el).append(new PhotoListItemView({ model: photo }).render().el);
        }, this);
        return this;
    }
});

PhotoListItemView = Backbone.View.extend({
    tagNAme: 'div',
    className: 'photo_box',

    template: _.template( $('#tpl_PhotoListView').html() ),

    initialize: function() {
        this.model.bind('destroy', this.close, this);
    },

    render: function() {
        $(this.el).html( this.template( this.model.toJSON() ) );
        return this;
    },

    close: function() {
        this.unbind();
        this.remove();
    }
});
4

1 に答える 1

20

まずPhotoListView、コレクションをラップしているのでthis.collection、ビュー内で使用new PhotoListView({ collection: c })して作成する必要があります。ビューは、collectionオプションを次のように扱いmodelます。

コンストラクター/初期化 new View([options])

[...] 渡された場合、ビューに直接アタッチされるいくつかの特別なオプションがあります: modelcollectionelid、および属性。classNametagName

正しい名前を使用すると、混乱を防ぐことができます。また、ビューにはいくつかの Underscore メソッドが既に混在しているため、 orthis.collection.each(...)の代わりに言うことができます。の代わりに使用することもできます。_.each(this.collection.models, ...)_(this.collection.models).each(...)this.$el$(this.el)

そして今、あなたの本当の問題に移ります。モデルごとのビューに 2 つのテンプレートを追加できます。

PhotoListItemView = Backbone.View.extend({
    template0: _.template($('#the-first-template-id').html()),
    template1: _.template($('#the-other-template-id').html()),
    //...
});

そして、どちらを使用するかを指定するオプション:

initialize: function(options) {
    this.template = this['template' + options.template_number];
    //...
}

group次に、コレクション ビューからオプションを指定するだけです。アンダースコアは、反復インデックスをコールバック関数に 2 番目の引数として渡すため、どちらを使用eachするかを判断するために少し整数演算が必要です。template_number

this.collection.each(function(photo, i) {
    // Grouped in threes and you're alternating between two templates.
    var n = Math.floor(i / 3) % 2; 
    var v = new PhotoListItemView({ model: photo, template_number: n });
    this.$el.append(v.render().el);
}, this);
于 2012-07-04T22:14:00.880 に答える