1

更新:我找到了一个与第一个答案略有相同的解决方案。但实际上我想知道是否有一种使用 RequireJS 的方式,无需在 views 中使用特殊的 var 或参数即可。这是我的解决方案:

define(['resthub', 'backbone', 'views/myModule/parent-view', 'views/myModule/a-view'],
function(Resthub, Backbone, ParentView, AView) {

    var ParentView = Backbone.View.extend({

        // Stuff before

        buildAView : function(aViewObject){
            var aView = aViewObject || AView;

            // Enought source code before and after those following lines
            // that I don't want to duplicate in ChildView
            this.aView = new aView();
            this.aView.render();
        }

        // Stuff after

    });

    return ParentView;
});

我尝试在 Backbone 项目中使用最大的继承,这些依赖项由 RequireJS 管理,以避免重复代码。事实上,我创建了一个扩展基本视图的新视图。基本视图有一个我想要覆盖的依赖项。但即使我尝试覆盖,也会采用原始​​依赖项,而不是新依赖项。请注意,我被迫继承。

这是我想要做的:

我继承的基本视图:

define(['resthub', 'backbone', 'views/myModule/parent-view', 'views/myModule/a-view'],
function(Resthub, Backbone, ParentView, AView) {

    var ParentView = Backbone.View.extend({

        // Stuff before

        buildAView : function(){
            // Enought source code before and after those following lines
            // that I don't want to duplicate in ChildView
            this.aView = new AView();
            this.aView.render();
        }

        // Stuff after

    });

    return ParentView;
});

然后查看我尝试创建的内容。我想要的是 buildAView() 函数采用 b-view 中名为 AView 的新依赖项,它包含与 a-view 中不同的源代码。

define(['resthub', 'backbone', 'views/myModule/parent-view', 'views/myModule/b-view'],
function(Resthub, Backbone, ParentView, AView) {

    var ChildView = ParentView.extend({

        // Stuff before

        render: function() {

            ParentView.__super__.render.apply(this, []);

            /* some stuff inbetween*/

            this.buildAView();
        }

    });

    return ChildView;
});

谢谢 :)

4

1 回答 1

0

问题是它AView绑定到它被注入的函数,所以当你调用buildAView它时,使用AView注入到ParentView模块中的那个。但是有一个简单的方法可以解决这个问题。只需保存AView为您的视图的属性。

define(['resthub', 'backbone', 'views/myModule/parent-view', 'views/myModule/a-view'],
function(Resthub, Backbone, ParentView, AView) {

    var ParentView = Backbone.View.extend({

        // Stuff before
        AView: AView,

        buildAView : function(){
            // Enought source code before and after those following lines
            // that I don't want to duplicate in ChildView
            this.aView = new this.AView();
            this.aView.render();
        }

        // Stuff after

    });

    return ParentView;
});

define(['resthub', 'backbone', 'views/myModule/parent-view', 'views/myModule/b-view'],
function(Resthub, Backbone, ParentView, AView) {

    var ChildView = ParentView.extend({

        // Stuff before
        AView: AView,

        render: function() {

            ParentView.__super__.render.apply(this, []);

            /* some stuff inbetween*/

            this.buildAView();
        }

    });

    return ChildView;
});
于 2013-08-19T18:32:56.533 回答