Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize your backbone app within require.js after external callback

Normally you load in an Backbone App using require.js during page load

<script data-main="js/main" src="js/libs/require/require.js"></script>

which loads some dependencies, and launches the app.

If your app requires manipulation of the DOM, you can use the domReady plugin

require(['domReady','app' ], function (domReady, App) {
  domReady(function (App) {
     App.Initialize()
  }):
});

But my application communicates with a Flash API. I need to wait till the flash plugin is done loading it's own xml. I fire a callback back to javascript when this is done. This callback needs to fire the app.initialize() with the dependencies as in require.js

The first method and second method (waiting for dom) doesn't ensure the flash api is available yet. So how can I Initialize the app, so that app.js has its dependencies and the flash api is available. Or formulated differently: How can I initialize require.js through a javascript event/callback

Update: Apparently, this would suffice:

<script data-main="js/main" src="js/libs/require/require.js"></script>
<script type="text/javascript">
    function init(){
        require(['framework/app'], function(App){
          App.initialize();
        });
    }       
</script>

The flash plugin can just call window.init() to start the app. Downside would be that stuff like jQuery gets loaded when the app gets initialized. This could lead intoo a small delay before stuff shows.

I eonder if, when I load jquery in the head/end of body, require.js would reload/instantiate another copy of jquery, or read from cache/dom

like image 793
Jareish Avatar asked Jan 05 '12 12:01

Jareish


1 Answers

You could take advantage of requirejs shim config, which will allow you to define a 'export' for specified require modules. This export will be the value cached on the global context and would be available as the callback function to use:

<script data-main="js/main" src="js/libs/require/require.js"></script>
<script type="text/javascript">
    requirejs.config({
        shim: {
            'framework/app': {
                exports: 'App'
            }
        }
    });
    require(['framework/app'], function(App){});
</script>

From here, your code that calls back a javascript function can just call:

App.initialize();
like image 111
Mark Roper Avatar answered Sep 28 '22 07:09

Mark Roper