如何处理主干marionette初始化程序中的异步代码

Bob*_*ley 6 backbone.js marionette

我正在尝试使用marionette插件组合骨干应用程序,并且在使初始化程序按照我预期的方式工作时遇到一些麻烦.我有以下代码:

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); // <- 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); // <- THIS returns 'undefined' BEFORE the console.log in the initializer above
});
Run Code Online (Sandbox Code Playgroud)

请注意上面的代码中我有两个console.log调用,一个在初始化程序中,一个在initialize:after处理程序中.两者都记录相同的对象属性.正如你所看到的,就是我遇到的是,console.log在呼叫initialize:after处理程序获取调用之前那个在success初始化的处理程序.我意识到这是因为初始化程序中有一个异步调用...我需要知道的是,在应用程序中执行任何其他操作之前,如何确保初始化程序中的所有异步代码都已完成?这有一个很好的模式吗?我没有在文档中找到任何指示如何正确处理此问题的内容.

谢谢.

Der*_*ley 7

在应用程序中执行任何其他操作之前,如何确保初始化程序中的所有异步代码都已完成?

不要使用该initialize:after活动.相反,从success调用中触发您自己的事件,然后绑定您的应用程序启动代码.

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;

            // trigger custom event here
            MyApp.vent.trigger("some:event:to:say:it:is:done")

        }
    });
});

// bind to your event here, instead of initialize:after
MyApp.vent.bind('some:event:to:say:it:is:done', 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);
});
Run Code Online (Sandbox Code Playgroud)

这样您就可以在异步内容完成后触发事件,这意味着在初始异步调用返回并设置完成后,处理程序中的代码才会运行.

  • 没什么好蠢的.如果你不知道答案,这是不明显的:) (2认同)