jQuery是否具有dojo.hitch()的等效项? [英] does jquery have an equivalent of dojo.hitch()?
问题描述
请原谅我的无知,因为我对jquery不那么熟悉.是否有与 dojo.hitch()等效的东西?它返回一个保证在给定范围内执行的函数.
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.
-编辑-
根据要求,这是一个示例.我经常使用挂钩来确保回调在正确的对象内执行.例如,假设我有一个名为doSomethingAsync
的实用程序方法,并向其传递了一个回调函数.即使没有使用Utility方法执行Ajax调用,我也可以确保使用Hitch可以在特定范围内执行该函数:
-- 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));
}
}
没有障碍,回调函数可能会在不同的范围内执行,并且会抛出错误,并且未定义this.flag
.但是,通过挂钩可以保证在execptedScopeObj
中执行.
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
.
推荐答案
我知道已经回答了,但是没有正确回答.我相信 jQuery.proxy
是您要寻找的东西.
I know this has been answered, but not correctly. jQuery.proxy
is what you are looking for I believe.
更新
很多年后,经过许多JavaScript工作之后,并且由于浏览器兼容性不再是一个问题,因此我剥离了jQuery的使用之后,我建议使用 jQuery.proxy
,如 @bobince建议.尽管这仍然是对原始问题的正确答案,但我还是不得不将人们引导到一种通用的解决方案,而不是依赖jQuery.
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.
这篇关于jQuery是否具有dojo.hitch()的等效项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!