如何在同一模块内调用函数? [英] How to call a function within the same module?

查看:57
本文介绍了如何在同一模块内调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力整理RequireJS以便整理我的应用程序.

I'm trying to get my head round RequireJS in order to tidy up my app.

我有几个模块和一个main.js脚本.

I have a few modules, and a main.js script.

在main.js中,我定义了一个包含一些AJAX函数的模块,以进行基本的API调用.

In my main.js, I am defining a module that contains a few AJAX functions, to make basic API calls.

在此"API"模块中,我首先调用一个AJAX函数,完成后,需要在相同的"API"模块中调用另一个AJAX函数(因为这些是异步任务,我想将它们链接起来)这样就可以了吗?!).

Inside this "API" module, I am first calling one of the AJAX functions, which after completion, needs to call a different AJAX function, inside the same "API" module (as these are Async tasks, I thought chaining them like this would be OK?!).

但是,仅在同一模块中调用函数名称是行不通的.

But, just calling the function name within the same module doesn't work.

那我该如何在同一模块中调用一个函数?

So how do I call a function within the same module?

这是我的"API"模块的设置方式:

Here is how my "API" module is set out:

define(function() {
    return {
        ajaxCall_A: function() {
            $.ajax({
                // settings
            }).done(function() {
                // now call ajaxCall_B
                ajaxCall_B(); // doesn't work!
            });
        },
        ajaxCall_B: function() {
            $.ajax({
                // settings
            }).done(function() {
                // finished
            });
        }
    }
}

推荐答案

对ajaxCall_A添加对本地对象的引用的以下更改将解决此问题,但是最好还是考虑 JQuery的Promise/deferreds ,因为这是链接Ajax调用的一种更好的方法.

The following change of adding a reference to the local object to the ajaxCall_A will fix the issue, however you'd probably be better off looking into JQuery promises/deferreds as this is a much nicer way of chaining Ajax calls.

define(function() {
    return {
        ajaxCall_A: function() {
            var self = this;
            $.ajax({
                // settings
            }).done(function() {
                // now call ajaxCall_B
                self.ajaxCall_B(); // doesn't work!
            });
        },
        ajaxCall_B: function() {
            $.ajax({
                // settings
            }).done(function() {
                // finished
            });
        }
    }
}

使用承诺的简要示例(未经测试):

Brief example using promises (untested):

define(function() {
        return {
            ajaxCall: function() {
                $.when(this.ajaxCall_A())
                 .then(this.ajaxCall_B())
                 .done(function() {
                    // finished
                 });
            },
            ajaxCall_A: function() {
                return $.ajax({
                    // settings
                });
            },
            ajaxCall_B: function() {
                return $.ajax({
                    // settings
                })
            }
        }
    }

这篇关于如何在同一模块内调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆