使用Require JS扩展Backbone对象的正确方法

时间:2013-03-28 21:37:59

标签: javascript backbone.js requirejs

我将requireJS与骨干结合使用:

define([

        "jquery",
        "underscore",
        "backbone",
        "models/modelA"

        ], function( $, _, Backbone, MyModel ) {

        var viewA = Backbone.View.extend({
            initialize: function() {
                 this.model = new MyModel();
            }
        });

        return viewA;

});

我想创建一个新的View模块ViewB,它具有与viewA相同的所有方法,但使用不同的模型代替modelA。我知道我可以覆盖初始化函数,但我想知道是否有更简洁的方法,以避免重复代码......

    define([

        "jquery",
        "underscore",
        "backbone",
        "views/viewA",
        "models/modelB"

        ], function( $, _, Backbone, ViewA, myModel ) {

        var viewB = ViewA.extend({
                initialize: function() {
                     this.model = new MyModel();
                }
        });

        return viewB;

    });

2 个答案:

答案 0 :(得分:1)

define(['views/ViewA'], function() {
    var ViewA = require('views/ViewA'), // require ViewA
    ViewB = ViewA.extend({
        // add all your ViewB specific methods/properties here
    });

    return ViewB; // return ViewB from the RequireJS module so it can be used elsewhere
});

答案 1 :(得分:1)

如果两个视图完全相同,只需传入实例化的模型,而不是在初始化中创建它。然后你只需要定义一个视图。

define([

        "jquery",
        "underscore",
        "backbone"
        // no model module needed here.

        ], function( $, _, Backbone ) {

        var viewA = Backbone.View.extend({
            initialize: function() {
            }
        });

        return viewA;

});

然后在require两个模型和视图的其他模块中:

var modelA = new ModelA();
var modelB = new ModelB();
// create 2 instances of ViewA with different model passed in
var viewA = new ViewA({model: modelA});
var viewB = new ViewA({model: modelB});

如果像这样创建,每个视图都会将this.model设置为您传入的实例。