我正在尝试使用CoffeeScript来设置AJAX回调函数,如下所示:
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');
});
}
我正在使用以下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"
它产生如下编译的JavaScript:
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");
}
}
});
};
我得到了错误(在上面标记的行上):
Uncaught TypeError: object is not a function
我的CoffeeScript在这里做错了什么?
答案 0 :(得分:2)
更改此
this.doAjax(function:(result)->
到这个
this.doAjax((result)->
coffeescript中的函数用() ->
声明。 function:() ->
使用名为function
的属性创建一个包含实际函数
答案 1 :(得分:-1)
实际上你试图回调函数在成功调用ajax之后执行某些操作,但是你正在调用该对象作为函数。定义一些函数并用它来回调。谢谢你,为了进一步的帮助,请报告给我。