Jake Wilson
Jake Wilson

Reputation: 91193

Callback: "Object is not a function"

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?

Upvotes: 1

Views: 178

Answers (2)

Nicolas Straub
Nicolas Straub

Reputation: 3411

change this

this.doAjax(function:(result)->

to this

this.doAjax((result)->

functions in coffeescript are declared with () ->. function:() -> creates an object with a property called function that contains the actual function

Upvotes: 2

Jayachandran Murugesh
Jayachandran Murugesh

Reputation: 111

Actually you are trying to callback function to perform some operation after successful ajax call, but you are calling the object as function.Define some function and use it to callback.thank you, for further assistance please report to me.

Upvotes: -1

Related Questions