我有2个相互交叉引用的模型。这看起来像这样:
MainModel:
define(
[ 'durandal/app', 'durandal/plugins/router', 'models/Shell', 'models/EditModel' ],
function (app, router, shell, editModel) {
//...
return {
//...
// This function should be accessible by the EditModel
update: function() {
//...
},
showEditView: function() {
// Initialise the EditModel with some data and show the according view afterwards
editModel.init('set some important stuff here...');
router.navigateTo('#/EditView');
}
//...
};
}
);
EditModel:
define(
[ 'durandal/app', 'durandal/plugins/router', 'models/Shell', 'models/MainModel' ],
function (app, router, shell, mainModel) {
//...
return {
//...
// This function should be accessible by the MainModel
init: function() {
//...
},
showMainView: function() {
// Update the the MainModel with some data and show the according view afterwards
mainModel.update('set new data here...');
router.navigateTo('#/MainView');
}
//...
};
}
);
不幸的是,这不起作用。如果我在MainView上加载我的页面并调用showEditView,变量editView是已知的,一切正常,但EditModel中的变量mainModel未定义,因此调用mainModel.update(...)
失败。
如果我在EditView上加载我的页面但是在“相反方向”(EditModel中的var mainModel已知,但MainModel中的editModel未定义),则会发生同样的事情。
这是一个已知问题,如果是这样的话:我怎样才能绕过它?
中发布了这个问题由于
答案 0 :(得分:2)
检查requierejs文档中的循环依赖关系http://requirejs.org/docs/api.html#circular。
循环依赖很少见,通常是您可能想要的标志 重新考虑设计。但是,有时它们是必需的,并且在那里 case,使用上面指定的require()。
对于main.js,将require作为依赖项添加,然后明确要求models/EditModel
应该这样做。复制其他模块或rethink the design
; - )。
define(
[ 'require', 'durandal/app', 'durandal/plugins/router', 'models/Shell', 'models/EditModel' ],
function (require, app, router, shell, editModel) {
//...
return {
//...
// This function should be accessible by the EditModel
update: function() {
//...
},
showEditView: function() {
// Initialise the EditModel with some data and show the according view afterwards
require('models/EditModel').init('set some important stuff here...');
router.navigateTo('#/EditView');
}
//...
};
}
);