如何在Backbone中重用多个视图的渲染功能?

时间:2013-09-24 19:22:26

标签: javascript backbone.js underscore.js backbone-views

我正在使用Backbone中的应用程序,我有多个具有相同渲染功能的视图:

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

如何在多个视图中重复使用此功能,以便遵循旧的DRY方式?

2 个答案:

答案 0 :(得分:1)

您可以使用此处指定的mixin模式:Proper way of doing view mixins in Backbone

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

var view = Backbone.View.extend({
//other methods
});

_.extend(view.prototype, renderable);

var myView = new view();
myView.render();

答案 1 :(得分:0)

扩展另一个视图

var BeefedupView = Backbone.View.extend({
    render: function () {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
});

var myView = BeefedupView.extend({
    // Do super cool stuff here...
});