streetlight
streetlight

Reputation: 5968

Passing object to Callback in Javascript

I'm trying to write a function with a callback -- I want to create an object, and then access that data in the callback.

Here is my function so far:

var getModelInfo = function(model, callback) {
      alert('called!')

      //This logs the correct model
      console.log(model);

      //The object I want to return
      return {
        "field1" : model.get("1"),
        "field2" : model.get("2"),
        "field3" : model.get("3"),
        "field4" : model.get("4")

      };

    }

    //Declared outside because I want to avoid 'this' issues
    var model_send = this.model;

    $(function() {
      alert('callback to be called')
      getModelInfo(model_send, function(data) {
        alert('call back called');

        // I want this to be the returned object
        console.log(data)

      });

    });

As of right now, 'callback to be called' alerts before 'called', but 'call back called' never alerts. How can I access that returned data in the callback?

Please feel free to let me know if I'm doing anything else wrong too!

Upvotes: 0

Views: 2869

Answers (1)

peirix
peirix

Reputation: 37741

You can call the callback with your new data instead of returning it:

var getModelInfo = function(model, callback) {
  alert('called!')

  //This logs the correct model
  console.log(model);
  callback({
    "field1" : model.get("1"),
    "field2" : model.get("2"),
    "field3" : model.get("3"),
    "field4" : model.get("4")
  });
}

Upvotes: 3

Related Questions