I have javascript 'class' in which jquery is a wrapping method for calling .ajax. I want to pass onSuccess and Honor Function handlers, but I'm not sure how. I can do this with plain old global works, but I'm trying to improve my JavaScript (from the Java background).
function testApp () {new X ());
function X () {// Init X, by calling Ajax, call AJAX to pass the Fanq. This._makeAjaxCall (initUrl, this.onSuccessInit, this.onError); // Make another component to call it another AJAX. _maxaxcoll (initUrl, this.onSuccessSomeOtherAjaxCall, this.onError); } X.prototype.onSuccessInit = function () {this.doStuff (...); } X. Prototype.OnSwedte Some other eXcocol = function () {this.doOtherStuff (...); } / ** * Call an AJAX, and call available success / error handler * / X.prototype._makeAjaxCall = function (url, onSuccessHandler, onError) {$. AJAX ({url: url, success: function (jsonData, TextStatus, XMLHttpRequest) {// If I have not called the user 'this', I have lost my reference / XUsx handler of my installation on X ; // If I use 'this', this indicates Ajax call object, not for my x object. This.onSuccessHandler ();}}); }
The problem is that when success is a callback $ Called by the Ajax function, the default reference window is used. You need to tell JQuery that you want a different reference so that you can do one of 3 things: $ Add a reference attribute to hash sent to Ajax , so my case can be: $. Ajax ({url: url, context: this, // will tell JQuery to use this right reference success: this.onSuccessHandler}); JQuery's $. Use the proxy function, such as: $ Ajax ({url: url, success: $ proxy (this.onSuccessHandler, this) // it will bind the right reference for the callback function}}; the cache variable As such, @ MVCRR has been suggested, although I encourage you to use self because it has happened to some extent javascript idioms var self = this; $ .ajax ({url: url, success: function} {self.onSuccessHandler (data);}}); Edit: < / P>
If you are javascript If you need to explain more depth of context and scope in checkout, then this article:
Comments
Post a Comment