1

I'm writing a Backbone + RequireJS project, and encountering the following situation:

Module A:

Backbone.Mediator.publish('ajax:fetch:in:module:b');

// I need to do something like **$.ajax(options).done()** here

Module B:

subscriptions: {
    'ajax:fetch:in:module:b': fetch
},

fetch: {
    $.ajax(options);
}

I've tried to hook $.ajax(options) under a shared namespace (like cache.temp = $.ajax(options)) in Module B, then calling cache.temp.done() inside Module A, but it happened way before $.ajax(options) was created so cache.temp was simply an undefined.

I guess one way to solve this problem is to create a deferred that delays the execution of the code before $.ajax(options) is ready, but am not very sure whether this is something doable. Or if there are better ideas around, I am all ears.

4

2 回答 2

4

这是 requirejs 与 jquery deferred 一起使用的简单示例:

模块A.js

define(['require', 'jquery'], function(require, $) {

    var deferred = $.Deferred();

    require(['moduleB'], function(moduleB) {
        deferred.resolve(moduleB);
    });

    return deferred.promise();

});

应用程序.js

require(['moduleA'], function(deferred) {
    deferred.done(function(moduleA) {
        console.log(moduleA);
    });
});
于 2012-11-09T14:26:14.607 回答
0

如果你有一个 ajax 或延迟的 obj,你可以使用$.whenand like this。$.then

$.when( ajax call).then( do other thing)

于 2012-10-17T11:46:50.593 回答