Extending jquery widget having a plain object modifies the base widget
I am facing an issue while extending jquery widgets, I have a widget which works fine.The code of the widget is
- $.widget( "xfaWidget.defaultWidget", {
$userControl : null,
_widgetName: "defaultWidget",
options : {
name: "",
value : null,
commitProperty: "value",
commitEvent: "exit"
/** more options **/
},
optionsMap: {
"access": function(val) {
//do something
},
"tabIndex": function(val) {
do something
},
"displayValue": function(val) {
//do something
},
},
eventMap: {
"focus" : "enter"
"blur" : "exit"
"click" : "click"
},
_create : function() {
this.widgetEventPrefix = "";
this.element.addClass(this._widgetName)
//widget creation code
_.each(this.optionsMap,function(val,key) {
if(typeof(val) === "function") {
val.apply(this,[this.options[key]]);
}
})
},
_setOption: function() {}
}
Now I need to extend this widget to create two other widgets, widget1 and widget2. In widget1 I have a new key in the optionsMap, but when that widget is created that key also is added into the defaultWidget and hence widget2 also has that key.
widget1
-
_maxChars: 0
optionsMap: {
"maxChars": function(val) {
if(this.options.value)
this.options.value.splice(0,this._maxChars)
},
},
so when I run all the function in the optionsMap for widget2 there is an error that _maxChars is not defined (which is correct, since widget2 doesn't supposed to have that property)
I then debugged jquery code and found that they modify the prototype of the base widget when you extend it with a new one. Is there a reason why jQuery does that ?
-
$[ namespace ][ name ].prototype = $.extend( true, basePrototype,
{
namespace: namespace,
widgetName: name,
widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name,
widgetBaseClass: fullName
}, prototype );