簡體   English   中英

將參數傳遞到骨干視圖

[英]Passing arguments to a backbone view

剛開始使用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');

您應該在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);

您應該始終處理集合的模型,而不僅僅是集合的數據。

您應該為視圖提供一個模型 ,並在渲染視圖時訪問模型的屬性。

var myModel = new Backbone.Model();

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM