StudioTime
StudioTime

Reputation: 23959

RequireJS - calling functions within the same file

I'm trying to call a function as a callback from another function within the same file.

Code below, shows no errors, but does nothing - is there a different/better way to do this?

I'm calling first function from require config file (require-main.js) and that works fine

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

Update: as above, tried caching this into var but still no joy

Upvotes: 0

Views: 434

Answers (3)

metal03326
metal03326

Reputation: 1263

Try this for the contents of your 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;
});

Upvotes: 3

Olivier Boiss&#233;
Olivier Boiss&#233;

Reputation: 18093

Maybe you should keep the reference to this keyword before calling the ajax function

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

Upvotes: 0

Ivan Shmidt
Ivan Shmidt

Reputation: 56

Should be

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

Upvotes: 1

Related Questions