我正在尝试使用 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 来执行此操作(这是在对象内):
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:
编译后的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");
}
}
});
};
我收到错误(在上面标记的行处):
Uncaught TypeError: object is not a function
我在这里的 CoffeeScript 做错了什么?
最佳答案
改变这个
this.doAjax(function:(result)->
到此
this.doAjax((result)->
coffeescript 中的函数是用 () ->
声明的。 function:() ->
创建一个具有名为 function
的属性的对象,该属性包含实际函数
关于javascript - 回调: "Object is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26880049/