库X
反复尝试调用它的方法foo
来严重损害我的插件Y
的用户体验。我的插件引入了在最终结果发生之前必须考虑的Y
任意逻辑。然而,当用户旅程(发生在模态窗口中)完成时,应该能够继续进行,就好像什么都没发生一样。shouldFooExecute
X.foo
Y
X
// This is an external library. I can't modify and shouldn't overwrite it.
x = {
// A method that completely screws my plugin
foo: function(){
/* nasty stuff */
}
}
// This is my widget!
y = {
// Init function, called when my plugin boots
init: function(){
// This scope handles the x.foo problem
void function rebindFoo(){
// Internal state
var shouldFooExecute = false;
// I need to be able to refer back to the original foo after I've temporarily rebound it
var x_foo = x.foo;
// Re-attach foo to its original definition & context
function rebindFooToX(){
// ECMAScript 5 browsers are fine!
if(Function.prototype.bind){
// x.foo is literally rebound to pretty much exactly what it was
x.foo = x_foo.bind(x);
}
// Others not so good when this function executes a second time
else {
x.foo = function rebound_foo(){
// An extra scope! Horrible. And it's recursive!
return x_foo.apply(x, arguments);
}
}
}
x.foo = function y_foo(){
// Stop and consider y's esoteric logic
if(shouldFooExecute){
// If it's fine, we rebind everything
rebindFooToX();
// This will have the intended effect
x.foo();
}
}
}
}
}
当我的插件在不支持绑定的浏览器上重新初始化时,问题就出现了。x.foo
最终引用rebound_foo
的是循环的。我可以编写任何逻辑来避免递归并在存在rebound_foo
的情况下使用现有的逻辑吗?