只有在特殊路由情况下,当在不同 Controller 中处理登录并通过全局事件机制路由到此处后,由路由器调用布局(请参阅要点链接)时,才会发生该错误。
只要重用现有 session 并且不处理任何登录,一切都很好。
主要代码在 this gist (第 #113 行错误“this.headerRegion”未定义
从登录和路由器进入 gist 模块的代码块...
loginSuccess: function (user) {
vent.trigger('user:login'); //notify all widgets we have logged in
app.router.navigate('home', { trigger: true });
}
...
return marionette.AppRouter.extend({
routes: {
'home' : 'home',
...
},
home: function() {
this._showPage('home');
},
...
_showPage: function (pageName, options) {
console.log("RouterShow " +pageName);
var that = this;
//make sure we are authenicated, if not go to login
if (!Parse.User.current())
pageName = 'login';
require(['./pages/' + pageName + '/Controller'], function (PageController) {
if (that.currentPageController) {
that.currentPageController.close();
that.currentPageController = null;
}
// line below loads the layout in the gist link
that.currentPageController = new PageController(options);
that.currentPageController.show(app.regionMain)
.fail(function () {
//display the not found page
that.navigate('/not-found', { trigger: true, replace: true });
});
});
}
...
define([
'marionette',
'./Layout',
'app'
], function (
Marionette,
Layout,
app
) {
'use strict';
return Marionette.Controller.extend({
show: function (region) {
var that = this, d = new Marionette.$.Deferred();
region.show(new Layout({ })); //this layout in gist link
return d.promise();
}
});
});
pageController.show()
在上述 block 的末尾附近调用要点中的布局区域
要重新创建仅在登录后发生的错误,我执行以下操作:
在要点的第 #57 行显示compoundView #1。
在复合 View #1 中点击要点第 40 行触发事件 ('roleList:getuser',)
将新 View #2 交换到用于第 #113、114 行第一个 View 的现有区域
错误 113,布局中不再存在“this.headerRegion”!
讨论 - 现在 IMO 布局扩展了 Marionett.ItemView,并且从源代码来看,它应该始终在调用 init 之前定义区域。构造函数在要点的第 #23 行检查 undef "this.headerRegion"。
我的代码在要点的第 18 - 23 行中重新实现了父类(super class)构造函数,看起来总是定义了“headerRegion”和“mainRegion”属性。但是,错误是:
Uncaught TypeError: Cannot call method 'show' of undefined Layout.js:113 Marionette.Layout.extend.getUserRelation
最佳答案
在您的情况下,诸如“headerRegion”之类的区域属性仅在 render() 之后可用,而不仅仅是 initialize() 后可用。来自 Marionette docs :
Once you've rendered the layout, you now have direct access to all of the specified regions as region managers.
在布局以要点之外的逻辑呈现之前,您必须触发这些事件(“roleItem:getrole”等)。相反,如果您想以这种方式实现 getUserRelation(),则需要先渲染。
关于javascript - 初始化后未定义 Marionette 区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21562058/