5

Backboneを使い始めたばかりです。コレクションをタイトル付きのリストとしてレンダリングできる一般的なビューがあります。現在、コレクションとタイトルをrenderメソッドに渡していますが、それは少し奇妙に思えます。より標準的な別の方法はありますか?

例えば:

var ListView = Backbone.View.extend({
    template: _.template([
        "<div>",
        "<% if (title) { %><h2><%= title %></h2> <% } %>",
        "<% if (items.length > 0) { %>",
        "<ul>",
            "<% items.each(function(item) { %>",
            "<%= itemTemplate(item) %>",
            "<% }); %>",
        "</ul>",
        "<% } else { %><p>None.</p><% } %>",
        "</div>"
    ].join('')),

    itemTemplate: _.template(
        "<li><%= attributes.name %> (<%= id %>)</li>"
    ),

    render: function(items, title) {
        var html = this.template({
            items: items /* a collection */,
            title : title || '',
            itemTemplate: this.itemTemplate
        });

        $(this.el).append(html);
    }
});

var myView = new ListView({ el: $('#target') });
myView.render(myThings, 'My Things');
myView.render(otherThings, 'Other Things');
4

2 に答える 2

17

initialize()関数で属性を渡す必要があります。

initialize: function (attrs) {
    this.options = attrs;
}

したがって、ここでは次のように属性をオブジェクトとして渡します。

new MyView({
  some: "something",
  that: "something else"
})

これで、渡した値が、このインスタンス全体で this.options にアクセスできるようになりました。

console.log(this.options.some) # "something"
console.log(this.options.that) # "something else"

コレクションを渡すには、1 つの親ビューと 1 つのサブビューを作成することをお勧めします。

var View;
var Subview;

View = Backbone.View.extend({
    initialize: function() {
        try {
            if (!(this.collection instanceof Backbone.Collection)) {
                throw new typeError("this.collection not instanceof Backbone.Collection")
            }
            this.subViews = [];
            this.collection.forEach(function (model) {
                this.subViews.push(new SubView({model: model}));
            });
        } catch (e) {
            console.error(e)
        }
    },
    render: function() {
        this.subViews.forEach(function (view) {
            this.$el.append(view.render().$el);
        }, this);
        return this;
    }
});

SubView = Backbone.View.extend({
    initialize: function () {
        try {
            if (!(this.model instanceof Backbone.model)) {
                throw new typeError("this.collection not instanceof Backbone.Collection")
            }
        } catch (e) {
            console.error(e);
        }
    },
    render: function () {
        return this;
    }
});

testCollection = new MyCollection();
collectionView = new View({collection: testCollection});
$("body").html(collectionView.render().$el);

コレクションのデータだけでなく、常にコレクションのモデルを処理する必要があります。

于 2012-07-09T21:00:16.230 に答える
2

ビューのモデルが必要であり、ビューをレンダリングするときにモデルのプロパティにアクセスする必要があります

var myModel = new Backbone.Model();

myModel.set("myThings", myThings);
myModel.set("myOtherThings", myOtherThings);

var myView = new ListView({ model: myModel });
于 2012-07-09T21:00:07.443 に答える