I’m trying to bind an event handler using jQuery:
$(document).ready(function () {
var newsScrollerForPage = new NewsScroller();
newsScrollerForPage.init();
$('#scroller-left-a').bind('onclick', newsScrollerForPage.decreasePage());
});
<div class="scroller-left">
<a id="scroller-left-a" href="#">
<img src="/Images/Left-Scroller.jpg"/>
</a>
</div>
But I’m having a problem:
handler is undefined [Break On This
Error] if ( !handler.guid ) {
Is there anything wrong with the way I am trying to bind this event handler?
What you’re doing in this line:
…is calling your function, and passing its return value into
bind. (You’re also using the wrong name for the event.)Instead:
Three changes there:
Using “click”, not “onclick”.
Don’t call your function, refer to it.
Because I’m assuming that you want
thiswithin yourdecreasePageto refer tonewsScrollerForPage, I’m using$.proxyto ask jQuery to make that happen for us.$.proxyaccepts a function reference (newsScrollerForPage.decreasePage, note there are no()after that) and a context (newsScrollerForPage) and returns a new function that, when called, will call that function and set the context (thisvalue) during the call to the context provided.Alternately, instead of
$.proxyyou can just use a closure directly:That works because the anonymous function is a closure over the
newsScrollerForPagesymbol. But the advantage to$.proxy(other than the fact its arguments are backward, IMHO) is that if the scope you’re doing this in has a lot of data you don’t want closed over, it creates a more contained closure for you. (If that didn’t make sense, my article Closures are not complicated may help.)