请原谅我的无知,因为我不太熟悉jquery。有没有等同于dojo.hitch()的东西?它返回一个保证在给定作用域中执行的函数。
-- edit --按照要求,下面是一个示例。我经常使用hitch来确保回调是在正确的对象中执行的。例如,假设我有一个名为doSomethingAsync
的实用程序方法,并向它传递了一个回调函数。使用hitch,我可以确保函数在特定的作用域内执行,即使实用程序方法执行ajax调用等:
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
是未定义的。但是,有了hitch,它就可以保证在execptedScopeObj
中执行。
发布于 2010-01-10 06:43:38
不是的。至少在1.3.2中没有,因为我不知道1.4。但是,也有一些plugins
(function($) {
$.fn.hitch = function(ev, fn, scope) {
return this.bind(ev, function() {
return fn.apply(scope || this, Array.prototype.slice.call(arguments));
});
};
})(jQuery);
发布于 2010-01-10 06:48:47
博本斯提到的function.bind
是一个非常有用的工具。您可以使用它非常简单地重写hitch函数:
// The .bind method from Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
Function.prototype.bind = function(){
var fn = this, args = Array.prototype.slice.call(arguments),
object = args.shift();
return function(){
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
}
jQuery.hitch = function(scope, fn) {
if (typeof fn == "string") fn = scope[fn];
if (fn && fn.bind) return fn.bind(scope);
};
至少根据你链接的文档页面,这就是我看到函数工作的方式……
发布于 2011-06-11 01:24:26
//why not just:
(function($){
$.hitch = function(scope, fn){
return function(){
return fn.apply(scope, arguments);
}
}
})(JQuery);
//This works exactly like Dojo's hitch from what I can tell.
https://stackoverflow.com/questions/2035236
复制相似问题