I am trying to use CoffeeScript to setup an AJAX callback function like so:
The Pattern
function doAjax(callback)
{
$.ajax(url, data)
.done(function(){
// ... do stuff here ...
callback(true);
}).fail(function(){
callback(false);
});
}
function doSomething()
{
doAjax(function(result){
if (result == true )
console.log('success');
else
console.log('failed');
});
}
I am using the following CoffeeScript to do this (this is within an object):
CoffeeScript
doAjax: (callback) ->
$.getJSON(url)
.done( (data) ->
if something == true
callback(true)
else
callback(false)
).fail( () ->
callback(false)
)
doSomething: () ->
this.doAjax(function:(result)->
if result == true
console.log "true"
else
console.log "false"
It results in the following compiled JavaScript like this:
Compiled JS
MyObject.prototype.doAjax = function(callback) {
return $.getJSON(url).done(function(data) {
if (something == true) {
callback(true); // <--- The error happens here
} else {
callback(false);
}
}).fail(function() {
callback(false);
});
};
MyObject.prototype.doSomething = function() {
return this.doAjax({
"function": function(result) {
var message;
if (result === true) {
return console.log("true");
} else {
return console.log("false");
}
}
});
};
And I get the error (at the marked line above):
Uncaught TypeError: object is not a function
What am I doing wrong in my CoffeeScript here?
doAjax, but an object. The error seems pretty clear.this.doAjax(function:(result)->? Is that not how you define an anonymous function?doAjax, you do it the same() ->