Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to handle async code in a backbone marionette initializer
    primarykey
    data
    text
    <p>I'm trying to put together backbone application using the marionette plugin, and am having some trouble getting initializers to work the way I expected them to. I have the following code:</p> <pre><code>var MyApp = new Backbone.Marionette.Application(); MyApp.addRegions({ region1 : '#div1', region2 : '#div2' }); MyApp.Resources = { }; MyApp.bind('initialize:before', function (options) { // display a modal dialog for app initialization options.initMessageId = noty({ text : 'Initializing MyApp (this should only take a second or two)', layout : 'center', speed : 1, timeout : false, modal : true, closeOnSelfClick : false }); }); MyApp.addInitializer(function (options) { $.ajax({ url: options.apiUrl + '/my-app-api-module', type: 'GET', contentType: 'application/json; charset=utf-8', success: function (results) { MyApp.Resources.urls = results; console.log(MyApp.Resources.urls); // &lt;- THIS returns an object } }); }); MyApp.bind('initialize:after', function (options) { // initialization is done...close the modal dialog if (options.initMessageId) { $.noty.close(options.initMessageId); } if (Backbone.history) { Backbone.history.start(); } console.log(MyApp.Resources.urls); // &lt;- THIS returns 'undefined' BEFORE the console.log in the initializer above }); </code></pre> <p>Note in the code above that I have two <code>console.log</code> calls, one in the initializer, and one in the <code>initialize:after</code> handler. Both log the same object property. As you can see, what I'm experiencing is that the <code>console.log</code> call in the <code>initialize:after</code> handler is getting called <em>before</em> the one in the <code>success</code> handler of the initializer. I realize that this is because the initializer has an async call in it...what I need to know is, how can I make sure that all of the async code in my initializer(s) is complete before doing anything else in the application? Is there a good pattern for this? I've not found anything in the docs indicating how to handle this correctly.</p> <p>Thanks.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload