2012-04-29 37 views
1

複数の別々のインスタンスをサポートするためにプラグインを作成したとは思うが、私のjQueryプラグインの他のインスタンスが変更されているという奇妙な問題が生じています。別のjQueryプラグインインスタンスの属性がオーバーライドされています

私は裸の必需品にコードをダウン剥奪しました、そして、あなたはここでそれを試すことができます:http://jsbin.com/ajifoh/4/edit#html,live

あなたはそれがコンソールにleng: 0を表示すべきテキストボックスのいずれかでキーを押しますが、あなたの後の最初の時間何らかの理由で最初のものを起動させたのですが、2番目のものにも最初に挿入されたすべてのcomboPartsがあります...どうしましたか?

;(function($, window, document, undefined){ 

    var KeyCombinator = function(elem, options){ 
     this.$elem = $(elem); 
    }; 

    function ComboPart(keyCode){ 
    if (keyCode !== undefined){ 
     this.keyCode = keyCode; 
    } 
    } 
    function ComboData(){ 
    this.comboParts= []; 
    } 

    function set_insert(array, value){ 
    array.push(value); 
    } 

    KeyCombinator.prototype = { 
    comboData: new ComboData(), 

    eval_key_event: function(e){ 
     set_insert(this.comboData.comboParts, new ComboPart(e.keyCode)); 
    }, 

    init: function(){ 
     var $elem = this.$elem; 
     var that = this; 

     $elem.keydown(function(e){ 
     console.log('leng', that.comboData.comboParts.length); 
     that.eval_key_event(e); 
     }); 
    } 
    }; 

    $.fn.makeKeyCombinator = function(options) { 
    return this.each(function() { 
     new KeyCombinator(this, options).init(); 
    }); 
    }; 

})(jQuery, window, document); 

答えて

1

prototypeに追加されたプロパティは、1種類につき1回しか存在しません。 KeyCombinator.prototypeComboDataをインスタンス化するため、KeyCombinatorのすべてのインスタンスはComboDataの単一インスタンスを共有します。あなたがKeyCombinatorのインスタンスごとにComboDataの一意のインスタンスをしたい場合は、次のようなあなたのKeyCombinatorコンストラクタでそれをインスタンス化する必要があります。ここでは

var KeyCombinator = function(elem, options){ 
    this.$elem = $(elem); 
    this.comboData = new ComboData(); 
}; 

jsbinにおける実施例です。

関連する問題