如何在自己内部引用Backbone / Marionette View?

时间:2015-09-21 21:01:36

标签: javascript backbone.js constructor marionette backbone-views

MyView.js:

define(['app/models/MyModel'],
    function (MyModel) {
        return Mn.LayoutView.extend({
            template: '#my-template',
            className: 'my-classname',
            regions: {
                content: '.content-region',
                panel: '.panel-region'
            }
            initialize: function () {
                _.bindAll(this, 'childButtonClicked');
            },
            onShow: function () {
                this.getRegion('content').show(new AnotherView());
            },
            childEvents: {
                'some-child-click': 'childButtonClicked'
            },
            childButtonClicked: function (view) {
                var newView = new MyView({
                    model: new MyModel({
                        title: view.model.get('title')
                    })
                });
                this.getRegion('panel').show(newView);
            }
        });
    });

我正在尝试将MyView的实例嵌套在自身中。当我通过将所有内容转储到一个函数中来构建原型时,这正常工作,如下所示:

var MyView = Mn.LayoutView.extend({
  ...
  childButtonClicked: function(view) {
    var newView = new MyView({
    ...

现在我正在尝试将Views分成他们自己的文件并使用require.js,我无法弄清楚自引用视图的语法。

当我按原样运行此代码时,出现“MyView未定义”之类的错误。

如果我将它添加到require标头中,如下所示:

define(['app/models/MyModel', 'app/views/MyView'],
    function (MyModel, MyView) {

我收到错误'MyView不是函数'。

编辑解决方案:

标记的解决方案工作正常,我最终使用了明显的hindslght:

define(['app/models/MyModel'],
    function (MyModel) {
        var MyView = Mn.LayoutView.extend({
            template: '#my-template',
            className: 'my-classname',
            regions: {
                content: '.content-region',
                panel: '.panel-region'
            }
            initialize: function () {
                _.bindAll(this, 'childButtonClicked');
            },
            onShow: function () {
                this.getRegion('content').show(new AnotherView());
            },
            childEvents: {
                'some-child-click': 'childButtonClicked'
            },
            childButtonClicked: function (view) {
                var newView = new MyView({
                    model: new MyModel({
                        title: view.model.get('title')
                    })
                });
                this.getRegion('panel').show(newView);
            }
        });
        return MyView;
    });

1 个答案:

答案 0 :(得分:2)

您可以在模块中require()var MyView = require(app/views/MyView);

因此,想要一个更好的地方:

childButtonClicked: function (view) {
    var MyView = require(app/views/MyView);
    var newView = new MyView({
        model: new MyModel({
            title: view.model.get('title')
        })
    });
    this.getRegion('panel').show(newView);
}