Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does jquery have an equivalent of dojo.hitch()?

Tags:

jquery

Forgive my ignorance as I am not as familiar with jquery. Is there an equivalent to dojo.hitch()? It returns a function that is guaranteed to be executed in the given scope.

-- edit -- As requested, here is an example. I use hitch very frequently to ensure callbacks are executed within the right object. For example, let's say I have a utility method called doSomethingAsync and I pass it a callback function. With hitch, I can make sure the function is executed within a particular scope even if the utility method performs ajax calls and so forth:


expectedScopeObj = {
   flag: true,
   callback: function(){console.debug(this.flag);},
   main: function() {
     // without hitch the callback function would not find flag  
     core.util.doSomethingAsync(dojo.hitch(this, this.callback));
   }
}

Without hitch, the callback function could possibly be executed in a different scope and an error would be thrown with this.flag being undefined. However, with hitch it is guaranteed to be executed within execptedScopeObj.

like image 285
Lightbeard Avatar asked Jan 09 '10 22:01

Lightbeard


3 Answers

I know this has been answered, but not correctly. jQuery.proxy is what you are looking for I believe.

UPDATE

Many, many years later after lots of JavaScript work, and after stripping out my usage of jQuery since browser compatibility has become less of an issue, I would recommend using Function.prototype.bind over jQuery.proxy, as @bobince suggested. While this is still the correct answer to the original question, I feel obligated to direct people to a vanilla solution rather than relying on jQuery.

like image 146
LordZardeck Avatar answered Sep 27 '22 20:09

LordZardeck


[ADMIN EDIT: Note the much more popular answer, below.—danorton]

I'd go for function.bind, which will be the standard way of doing this in future versions of JavaScript. As well as fixing this , it allows you to pass arguments through to the target functions.

Until all browsers support it natively, you can hack support in yourself.

like image 41
bobince Avatar answered Sep 27 '22 20:09

bobince


No. Not in 1.3.2, at least, as I don't know about 1.4. There are, however, some plugins:

(function($) {
  $.fn.hitch = function(ev, fn, scope) {
    return this.bind(ev, function() {
      return fn.apply(scope || this, Array.prototype.slice.call(arguments));
    });
  };
})(jQuery);  
like image 30
Victor Nicollet Avatar answered Sep 27 '22 20:09

Victor Nicollet