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

RequireJS - calling functions within the same file

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

下面的代码没有显示任何错误,但什么也没做 - 有没有 different/better 方法可以做到这一点?

我从 require 配置文件 (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 中,但仍然没有任何乐趣

应该是

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 */
        });
 }

为您的 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;
});