I was following some of the coding samples from the book "Javascript: The Good parts".
One of the examples adds a new function to the Object prototype
Function.prototype.method = function(name, func) {
if ( !this.prototype[name] ) {
this.prototype[name] = func;
return this;
}
};
Object.method('superior', function(name) {
var that = this,
method = that[name];
return function() {
if ( method !== undefined ) {
return method.apply(that, arguments);
};
};
});
This is a way of simulating accessing methods from an object's prototype with the same name ( i.e. method overriding in classical OO programming ).
However, this causes an issue in the Init function of the event binding
var eventsToHandle = valueAccessor() || {};
I have a normal click data-bind for a HTML button
<button data-bind="click: someMethod">Click Me</button>
The eventsToHandle value returns the click function, but the superior function added to the Object prototype is also enumerated when the following statement
for(var eventNameOutsideClosure in eventsToHandle) {
...
}
The loop is executed twice, once for "click", the second for "superior". In the second iteration superior "event" is attempted to be bound to the ko handler, which fails.
You need to check if the function is owned by the eventsToHandle object or if it comes from the prototype chain by using the hasOwnProperty function and ignore appropriately.
for(var eventNameOutsideClosure in eventsToHandle) {
if (!eventsToHandle.hasOwnProperty(eventNameOutsideClosure)) {
continue;
}
...
}
I have a
jsFiddle that replicates this issue