0

我将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;

    });
4

2 回答 2

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
});
于 2013-03-28T21:43:08.680 回答
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设置为您传入的实例。

于 2013-03-28T23:49:18.140 回答