我处于以下情况。
代码(3)与代码(1)一起使用,但不适用于代码(2)。
IMH,原因是因为情况(2)的backendController模块在代码(3)之后异步加载。
我应该如何修复代码(3)以使其与代码(2)一起使用?

附言:
使用代码(2)的原因是因为它使页面加载更快。



(1)

define([
 '../../utils/backendController'
], function (backendController) {

    events: {
        'submit form': 'submitForm'
    },

    submitForm: function (event) {
        event.preventDefault();

        // in this way I can spy backendController object
        this.doSubmitForm(backendController);

        // in this way I can not spy backendController object
        // require(['../../utils/backendController', this.doSubmitForm);
        // see the code (2)

    }
});




(2)

define([], function () {

    events: {
        'submit form': 'submitForm'
    },

    submitForm: function (event) {
        event.preventDefault();

        // in this way I can not spy backendController object
        require(['../../utils/backendController', this.doSubmitForm);

    }
});




(3)

(function () {
    define([
        'backendController'
    ], function () {
        describe('when submitting a form', function () {
            beforeEach(function () {
                var mySpy = spyOn(backendController, 'myCall').andCallThrough();
                this.view.$el.find('form').submit();
            })
            it('backendController.myCall should be called', function () {
                expect(backendController.myCall.toHaveBeenCalled());
            });
        });
    });
}());

最佳答案

我想您已经知道为什么(1,3)可以工作了,无论如何都可以,因为backendController模块在(3)中的代码执行之前就已加载并定义了。

在情况(2)中,发生的情况是仅在提交表单时才需要backendController。所以到时候

var mySpy = spyOn(backendController, 'myCall').andCallThrough();


创建间谍,backendControllerundefined;)

现在您可以但不应该通过执行类似的操作来修改代码(2)


submitForm中创建一个以doSubmitForm解析的递延的值,或
保持(2)不变,并使测试适应要求backendController


但这太过分了。您应该只按照(1)中推荐的要求方式进行操作,它还具有其他一些优点,例如可以使用r.js优化器。

关于javascript - 如何监视异步加载的模块,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12409418/

10-10 09:16