1

ライブラリは、プラグインの UXに大きな損害を与えるために、Xそのメソッドを繰り返し呼び出そうとします。私のプラグインは、の最終結果が発生する前に考慮しなければならない任意のロジックを導入します。ただし、ユーザー ジャーニー(モーダル ウィンドウで行われる) が完了すると、何も起こらなかったかのように続行できるはずです。fooYYshouldFooExecuteX.fooYX

// 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する場合に既存のものを使用するために記述できるロジックはありますか?

4

2 に答える 2

0

https://github.com/kriskowal/es5-shimを使用Function.prototype.bindして、ネイティブでサポートされていないブラウザーにメソッドを追加できます。

于 2013-03-26T13:14:34.297 に答える
0

事実から7か月後なので、この問題はおそらくOBEですが、Xの定義方法によっては、継承を試すことができることに注意してください。

var x = function() {
    this.foo = function() {
        console.log("from x");
    };

    this.bar = function() {
        console.log("from x");
    };
}

var y = function() {
    this.foo = function() {
        console.log("from y");
    }
}

y.prototype = new x();

var test = new y();
test.foo(); // will output: from y
test.bar(); // will output: from x
于 2013-10-29T12:24:35.700 に答える