I’m having this weird problem where other instances of my jQuery plugin are getting modified even though I believe I’ve written my plugin to support multiple separate instances.
I’ve stripped down the code to the bare essentials, and you can test it out here: http://jsbin.com/ajifoh/4/edit#html,live
The first time you press a key in either textbox it should display leng: 0 in the console, but after you’ve triggered the first one for some reason the second one also has all the comboParts that were inserted for the first… What have I done wrong?
;(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);
Properties added to the
prototypeonly exists once per type. Since you instantiateComboDataon theKeyCombinator.prototype, all instances ofKeyCombinatorshare a single instance ofComboData. If you want a unique instance ofComboDatafor each instance ofKeyCombinator, you need to instantiate it in yourKeyCombinatorconstructor as such:Here is a working example in jsbin.