Reputation: 4188
I'm trying to get my head round RequireJS in order to tidy up my app.
I have a few modules, and a main.js script.
In my main.js, I am defining a module that contains a few AJAX functions, to make basic API calls.
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?
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
});
}
}
}
Upvotes: 2
Views: 1050
Reputation: 4844
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
})
}
}
}
Upvotes: 4
Reputation: 457
(function (define) {
return {
ajaxCall_A: function () {
$.ajax({
// settings
}).done(function () {
// now call ajaxCall_B
define.ajaxCall_B(); // it works now!
});
},
ajaxCall_B: function () {
$.ajax({
// settings
}).done(function () {
// finished
});
}
}
});
Try using like this.
Upvotes: -1