庫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
?
你爲什麼試圖替換x。 FOO?你可能會遇到其他插件的問題,因爲你綁定它等等。你不能只調用你自己的y_foo()而不是使用x.foo()嗎? – 2013-03-26 13:16:06
另外我想'x.foo = y_foo(){'是不正確的語法。 – 2013-03-26 13:17:43
@AramKocharyan - 感謝您指出錯字。潛在地遇到與其他插件有關的問題正是我爲什麼要花費這麼長的時間來將'x.foo'重新綁定到它的原始上下文,一旦我的模態的UX完成。我不是那種試圖調用'x.foo'的人(我不想稱之爲!) - 與之相關的事件是多方面的,並且不受我的控制。 – Barney 2013-03-26 14:00:36