【问题标题】:RequireJS - calling functions within the same fileRequireJS - 在同一个文件中调用函数
【发布时间】:2016-08-04 07:42:31
【问题描述】:

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

下面的代码没有显示错误,但什么也没做 - 有没有不同/更好的方法来做到这一点?

我正在从 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 */
            });
        }
    }
});

I've seen this question but I can't work this way as the order is not predetermined

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

【问题讨论】:

  • this.lines这是函数的引用,你实际上并没有调用它

标签: javascript requirejs


【解决方案1】:

试试这个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;
});

【讨论】:

    【解决方案2】:

    应该是

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

    【讨论】:

      【解决方案3】:

      也许你应该在调用 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 */
              });
       }
      

      【讨论】:

      • 他已经这样做了,无论如何 this 在这种情况下指的是对象,而不是函数
      • @Francescoes。顺便说一句,他的 var self = 这不在同一个地方,我认为我的解决方案应该有效。
      猜你喜欢
      • 1970-01-01
      • 2014-10-18
      • 2013-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-25
      • 2022-08-18
      • 1970-01-01
      相关资源
      最近更新 更多