将参数传递给骨干视图

时间:2012-07-09 20:54:45

标签: javascript collections backbone.js views

刚开始使用Backbone。我有一个通用视图,可以将集合呈现为带有标题的列表。我目前正在将集合和标题传递给render方法,但这看起来有点奇怪。还有另一种方式更规范吗?

E.g:

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');

2 个答案:

答案 0 :(得分: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"

要传递集合,我建议制作一个父视图和一个子视图:

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);

您应该始终处理集合的模型,而不仅仅是集合的数据。

答案 1 :(得分:2)

在渲染视图时,您应该为视图设置模型并访问模型的属性。

var myModel = new Backbone.Model();

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

var myView = new ListView({ model: myModel });