When I try to bind a class method to an event, I get a error "Cannot read property 'bind' of undefined." This tells me that the object that I'm binding to is undefined, yet it does exist and can be called. Consider the following code:
someClass = ({
event: function(workObject, event, action) {
workObject.addEventListener(event, window[action].bind(null, arguments[3]));
},
methodEventHandler: function(param) {
// Do Something
},
});
function someEventHandler(param) {
// Do Something
}
Now when I try to bind the event listener like this:
someClass.event(workObject, "click", "someEventHandler", someParameter);
It works. However, when I try to bind it this way:
someClass.event(workObject, "click", "someClass.methodEventHandler", someParameter);
It fails with the afore mentioned error. My question is why? I think it has something to do with scope since the regular function is in the global context and works but the method, which is not in the global scope, fails. I fixed this using a wrapper function, but I would really like to know why it is exhibiting this behavior. I'm doing it this way so I can bind event handlers using the function name as a string. Makes it easier to deal with when generating web pages dynamically. The only thing that I can think of is that the name of the event handler needs to be in a certain format, but I'm not sure what that looks like. Any insights?
I have dome some research on this and I found lots of questions and answers about how to bind handlers to events and such using various frameworks like jQuery, AngularJS, and Node.js. Some of those are here:
How to access the correct `this` inside a callback?