0

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!

5
  • 2
    You never executed callback. Commented Apr 10, 2013 at 19:56
  • What does this refer to in this line: var model_send = this.model;? Commented Apr 10, 2013 at 19:56
  • Thats because you never call callback in your getModelInfo function Commented Apr 10, 2013 at 19:56
  • @Asad The this refers to a Backbone model scope Commented Apr 10, 2013 at 20:19
  • @streetlight You should add the Backbone tag then, or at least mention this in your question. Commented Apr 10, 2013 at 20:21

1 Answer 1

3

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")
  });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.