event binding's init function find functions from prototype chain

31 views
Skip to first unread message

slan...@gmail.com

unread,
Sep 17, 2012, 8:13:54 PM9/17/12
to knock...@googlegroups.com
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(namefunc{
    if !this.prototype[name{
        this.prototype[namefunc;
        return this;
    }
};

Object.method('superior'function(name{
    var that this,
        method that[name];
    
    return function({
        if method !== undefined {
            return method.apply(thatarguments);
        };
    };
}); 

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
Reply all
Reply to author
Forward
0 new messages