简体   繁体   中英

JQuery Deferred Ajax, save result in the calling object

I'm pretty new to the whole prototype idea in Javascript, from what I've gathered so far it's basically a template for new objects to be created from.

Anyway, I have an object "Schedule" that is a child of "PageObject". Here is a function from the Schedule object:

Schedule.prototype.serviceSuccessFunction = function(data, status, xqr) {
  var ld;
  ld = Schedule.__super__.serviceSuccessFunction.call(this, data, status, xqr);
  ld.done($.proxy(function(x) {
    return console.log(this);
  }, this));
  ld.done($.proxy(this.render, this));
  return ld.done($.proxy(this.modernizeAndShow, this));
};

And here is what the PageObject's function looks like (being called from it's child):

PageObject.prototype.serviceSuccessFunction = function(data, status, xqr) {
  $.mobile.loading("show");
  return $.when($.mobile.loadPage("pages/" + this.url, {
    pageContainer: $("#" + this.loadOptions.loadSection)
  }));
};

As you can see, the PageObject is returning the deferred object for when this mobile page loads. I then have custom .done() functions in the Schedule object. These done functions will render based on what the "data" parameter is.

This "data" parameter comes from another deferred object (using $.ajax). When I breakpoint on the first line of the Schedule success function, "data" is properly filled in with what the ajax call returned.

Now my problem is I want to be able to call a different function in Schedule with the data as a parameter, or save the data on the Schedule object itself. How do you suppose I would pass in the data object into these functions?

When I breakpoint on the return console.log(this); line, "this" is the Schedule object thanks to the $.proxy. But I am unable to find "data" (which makes sense I suppose). Ideally I would like to pass in "data" as a parameter and do something like

ld.done($.proxy(function(data) {
  this.rData = data;
}, this));

But "data" or "x" above is just the url of the .ajax call.

I might have misunderstood but can you not just place this.rData = data; outside the "done" function:

Schedule.prototype.serviceSuccessFunction = function(data, status, xqr) {
  var ld;
  ld = Schedule.__super__.serviceSuccessFunction.call(this, data, status, xqr);

  this.rData = data;

  ld.done($.proxy(function(x) {
    return console.log(this.rData);
  }, this));
  ld.done($.proxy(this.render, this));
  return ld.done($.proxy(this.modernizeAndShow, this));
};

The rData is then available inside your delegate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM