RequireJS-在同一文件中调用函数

RequireJS - calling functions within the same file

本文关键字:调用 函数 文件 RequireJS-      更新时间:2023-09-26

我正试图从同一文件中的另一个函数中调用一个函数作为回调。

下面的代码没有显示错误,但什么也没做——有什么不同/更好的方法吗?

我正在调用require-config文件(require-main.js)中的第一个函数,它在中运行良好

define(['require-main'], function() {
    require(['getJSON'], function(getJSON) {
        getJSON.stations();
    });
});

getJSON.js

define(['jquery', 'domChange', 'setUp'], function($, domChange, setUp) {
    var self = this;
    return {
        stations: function() {    
            $.get('/js/ajax/stations.json', function(sol) { /* local JSON */
                tmv.stations = sol;
                console.log(sol); /* this is fine */
                self.lines; /* <-- call next function */
            });
        },
        lines: function() {
            console.log('foo'); /* NOT called */
            $.get('/js/ajax/lines.json', function(lines) { /* local JSON */
                /* do something */
            });
        }
    }
});

我看到了这个问题,但我不能这样做,因为订单不是预先确定的

更新:如上所述,尝试将this缓存到var中,但仍然没有joy

getJSON.js:的内容进行此操作

define(['jquery', 'domChange', 'setUp'], function($, domChange, setUp) {
    var getJSON = {
        stations: function() {    
            $.get('/js/ajax/stations.json', function(sol) { /* local JSON */
                tmv.stations = sol;
                console.log(sol); /* this is fine */
                getJSON.lines(); /* <-- call next function */
            });
        },
        lines: function() {
            console.log('foo'); /* NOT called */
            $.get('/js/ajax/lines.json', function(lines) { /* local JSON */
                /* do something */
            });
        }
    }
    return getJSON;
});

应该是

tmv.stations = sol; console.log(sol); /* this is fine */ this.lines(); /* <-- Actually calls the function */

在调用ajax函数之前,也许您应该保留对this关键字的引用

stations: function() {    
        var self = this;
        $.get('/js/ajax/stations.json', function(sol) { /* local JSON */
            tmv.stations = sol;
            console.log(sol); /* this is fine */
            self.lines(); /* <-- call next function */
        });
 }