Backbone Marionette: Marionette.Application causin

2019-04-17 09:38发布

I'm trying to include the App instance to use it's event aggregator as shown here

I get an error when I include the instance in a view.

Kicking things off in the Requirejs config file, from App.Bootloader.js:

require(['App'], function (App){
      App.start();
      });

from 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;
});

From 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)
      }

   });

});

From /folder/folder/View.js:

define(function (require){

      //...requisite includes $, _, Backbone, Marionette ...

     var App = require('App');
     return Marionette.ItemView.extend({});
});

Where I get the error "'Error: Module name 'App' has not been loaded yet for context: _"

Any ideas? Lemme know if you need more information.

4条回答
我欲成王,谁敢阻挡
2楼-- · 2019-04-17 09:43

I'm also looking for a good way to handle with this kind of situations using marionette and require.js

I have worked on a solution but I don't know if it is the best way, here are my thoughts:

  • the application has actions attached to events without knowing about the views
  • inside the view we use triggers to attach actions to events
  • the connection of actions between the view and the application is made inside the view

This is a possible solution:

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
}); 

it is important to remember that require is asynchronous, so when we use it like this it will not be executed immediately:

require( ['some-module'], function( someModule ){ 
   // do something, but only as soon as someModule is loaded 
});

we can prepare objects wich point to the external context, like this:

var thisName = this;
require( ['some-module'], function( someModule ){ 
   // access to external this using thisName
});
查看更多
Luminary・发光体
3楼-- · 2019-04-17 09:51

user1248256 is correct. I had the same problem. My App needed a controller and my Controller needed App.

By passing in the controller (view for your code) as part of options I don't have to add it to the require.js definition.

//data-main:
define(function(require) {
    var   $                 = require("jquery"),
        _                   = require("underscore"),
        App                 = require("app/App"),
        PublicRouter        = require("routers/DesktopRouter"),
        PublicController    = require("routers/publicController");

    var options = {
        publicController  :   PublicController,
        publicRouter      :   PublicRouter

    }

    App.start(options);
});

Now in App I don't have to "require" the PublicController

//App:
define(['jquery', 'backbone', 'marionette', 'underscore'],
function ($, Backbone, Marionette, _) {
    var App = new Marionette.Application();
    ...snip...
        console.log("Creating Routers");
        App.Routers = {};
        // Connect controllers to its router via options
        // init router's router/controller
        App.Routers.publicRouter = new options.publicRouter.Router({
            controller: options.publicController
        });
    });

Hope that helps.

Andrew

查看更多
beautiful°
4楼-- · 2019-04-17 09:55

I generally think it's bad practice to use the app's EventAggregator when using requireJS, if for no other reason than it's really easy to wind up with a circular reference.

Just define a separate EventAggregator module that can be required by App, View, and Layout, then add it to the dependencies of any module that needs it.

查看更多
相关推荐>>
5楼-- · 2019-04-17 10:02

I guess you have a problem with circular dependencies. App needs View and View needs App. Hmm… But why View requires App? I can't figure it from your code. In the end, are you sure View needs App? By the way, I think you mistyped. The first From /folder/folder/View.js probably should be From Layout.js.

查看更多
登录 后发表回答