JQuery.proxy is your friend

I'm a Javascript/JQuery newbie and one of the first puzzles that I ran into is callback functions and the value of "this".

You set up a callback handler like so:


jQuery.getJSON('/address/list', this.myCallback);


And you expect that when your callback is invoked that "this" will be set to the value of the enclosing object:


myCallback: function(json) {
    this.doSomething(); // doesnt work!
},
doSomething: function() // ...




What you (not so quickly) discover is that JQuery sets the value of "this" to the DOM object (or the element within the DOM that triggered the callback).  It is *not* set to the object that holds your callback function!

The solution is to use JQuery's proxy wrapper:


jQuery.getJSON('/address/list', JQuery.proxy(this.myCallback,this));


You will want to read  this and this for a full explanation.

BTW - none of these results floated to the top of the Google machine. If you are newbie, you probably don't know that you need JQuery.proxy :-).  Hopefully this will help





Comments

Popular posts from this blog

Introducing ds-operator, the ForgeRock Directory Services Operator for Kubernetes

Automating OpenDJ backups on Kubernetes

OAM R2 REST APIs for Policy Management