我正在尝试包含应用程序实例以使用其事件聚合器,如图所示 here
当我将实例包含在 View 中时,出现错误。
在 Requirejs 配置文件中启动 App.Bootloader.js:
require(['App'], function (App){
App.start();
});
来自 App.js:
define(function (require){
//...requisite includes $, _, Backbone, Marionette ...
var Layout = require('Layout');
var App = new Marionette.Application();
App.addRegions({
main: '#view_content'
});
App.addInitializer(function (){
App.main.show(new Layout());
//... adding router etc ...
Backbone.Marionette.TemplateCache.loadTemplate = function (template, callback){
callback.call(this, Handlebars.compile(template));
};
Backbone.history.start();
});
return App;
});
来自 Layout.js:
define(function(require){
var View = require('folder/folder/View');
//template contains #sub div
var template = require('text!template.html');
return Marionette.Layout.extend({
template: template,
regions: {
sub: '#sub'
},
initialize: function(){
//wait till template is rendered in dom
_.defer(function(region){
region.sub.show(new View());
}, this)
}
});
});
来自/folder/folder/View.js:
define(function (require){
//...requisite includes $, _, Backbone, Marionette ...
var App = require('App');
return Marionette.ItemView.extend({});
});
我收到错误“'错误:模块名称'App'尚未加载上下文:_”
有什么想法吗?如果您需要更多信息,请告诉我。
最佳答案
我也在寻找一种使用 marionette 和 require.js 处理这种情况的好方法
我已经找到了解决方案,但我不知道这是否是最好的方法,这是我的想法:
- 应用程序在不知道 View 的情况下将操作附加到事件
- 在 View 中,我们使用触发器将操作附加到事件
- View 和应用程序之间的操作连接是在 View 内部进行的
这是一个可能的解决方案:
app.js
define( [ 'underscore', 'jquery', 'backbone', 'marionette' , 'view'],
function( _, $, Backbone, Marionette, View ) {
var app = new Marionette.Application();
app.addRegions({ content: '#content'})
app.on( "initialize:after", function(){
console.log( 'after init', app)
var view = new View();
app.content.show( view );
});
// this is the action that we would like to call from the view
app.vent.on( 'viewClick', function(){ console.log( 'clicked on view' )})
return app;
});
View .js
define( [ 'underscore', 'jquery', 'backbone', 'marionette' ],
function( _, $, Backbone, Marionette ) {
var View = Marionette.ItemView.extend({
template: '#view',
triggers: {
'click': 'clicked'
},
initialize: function(){
// thisView will be referring to the view instance
var thisView = this;
// we require the app because we need access to the event aggregator
require(['app'], function( app ){
// when our event is triggered on our view
thisView.on( 'clicked', function(){
// we trigger an event on the application event aggregator
app.vent.trigger( 'viewClick' )
});
});
}
})
return View
});
重要的是要记住 require 是异步的,所以当我们像这样使用它时,它不会立即执行:
require( ['some-module'], function( someModule ){
// do something, but only as soon as someModule is loaded
});
我们可以准备指向外部上下文的对象,如下所示:
var thisName = this;
require( ['some-module'], function( someModule ){
// access to external this using thisName
});
关于javascript - Backbone Marionette : Marionette. 应用程序导致 Require.js 模块加载错误, "' 错误:模块名称 'App' 尚未加载上下文:_”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11056703/