0

我正在尝试编写一个带有回调的函数——我想创建一个对象,然后在回调中访问该数据。

到目前为止,这是我的功能:

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)

      });

    });

截至目前,“callback to be called”在“callback”之前发出警报,但“callback call”从不发出警报。如何在回调中访问返回的数据?

如果我做错了什么,请随时告诉我!

4

1 回答 1

3

您可以callback使用新数据调用而不是返回它:

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")
  });
}
于 2013-04-10T19:56:03.823 回答