Reputation: 650
I have been trying to figure out the best way to obtain my Marionette application's instance throughout my app. I am using requirejs, however I cannot figure out if it is possible to grab the actual instance of the app through require.
I have used Backbone.Wreqr.EventAggregator and callbacks in order to grab the app instance however that feels extremely messy.
I would also like to avoid passing the app instance through the constructors of my various views as well, as I feel there should be a better way.
This is at the bottom of my data-main file:
define('MyApp', ['App'], function (App) {
return new App();
});
require(['MyApp'], function (app) {
app.start();
Backbone.history.start({
pushState: true
});
});
This code works fine and boots up the app, however in my sub views and other components the app ends up being undefined. For example app is undefined in this scenario:
define([
'marionette',
'../controllers/Controller',
'MyApp'
], function (Marionette, Controller, app) {
var controller = new Controller();
var Router = new Marionette.AppRouter({
controller: controller,
appRoutes: {
'home' : 'showUserHome'
}
});
return Router;
});
Upvotes: 0
Views: 407
Reputation: 2721
I'm not sure what you've missed in your application, but you're on the right track. Here's a working example to show that you can share the app
instance similarly to the code that you've posted.
define('MyApp', function(){
return new Mn.Application();
});
define('LayoutView', ['MyApp'], function(app){
return Backbone.View.extend({
render: function(){
this.$el.append('App Started');
app.trigger('hey:app');
return this;
}
});
});
define('StuffOnStart', ['MyApp', 'LayoutView'], function(app, LayoutView){
app.on('start', function(){
var layoutView = new LayoutView();
$(document.body).empty().append( layoutView.render().el );
});
});
require(['MyApp', 'StuffOnStart'], function(app){
app.on('hey:app', function(){
$(document.body).append( '[<code>app</code> object is successfully shared between require.js modules]' );
});
app.start();
});
<script src='http://code.jquery.com/jquery.js'></script>
<script src='http://underscorejs.org/underscore.js'></script>
<script src='http://backbonejs.org/backbone.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/backbone.marionette/2.4.3/backbone.marionette.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.20/require.min.js'></script>
Loading...
Upvotes: 1