我正在尝试使用 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
});
请注意,在上面的代码中,我有两个
console.log
调用,一个在初始化器中,一个在 initialize:after
中处理程序。两者都记录相同的对象属性。如您所见,我遇到的是 console.log
调用initialize:after
处理程序在 success
中的处理程序之前被调用初始化程序的处理程序。我意识到这是因为初始化程序中有一个异步调用......我需要知道的是,在应用程序中执行任何其他操作之前,如何确保我的初始化程序中的所有异步代码都是完整的?这有一个好的模式吗?我在文档中没有找到任何指示如何正确处理此问题的内容。谢谢。
最佳答案
how can I make sure that all of the async code in my initializer(s) is complete before doing anything else in the application?
不要使用
initialize:after
事件。相反,从 success
触发您自己的事件调用,然后从那个绑定(bind)你的应用程序启动代码。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);
});
这样,您将在异步内容完成后触发事件,这意味着处理程序中的代码将在初始异步调用返回并设置好之后才会运行。
关于backbone.js - 如何在 Backbone Marionette 初始化程序中处理异步代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11508225/