开发者

Having a problem binding an event handler in this way whats wrong?

开发者 https://www.devze.com 2023-03-17 18:04 出处:网络
I\'m trying to bind an event handler using jQuery: $(document).ready(function () { var newsScrollerForPage = new NewsScroller();

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"/>
   开发者_JAVA技巧     </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:

$('#scroller-left-a').bind('onclick', newsScrollerForPage.decreasePage());

...is calling your function, and passing its return value into bind. (You're also using the wrong name for the event.)

Instead:

$('#scroller-left-a').bind('click', $.proxy(newsScrollerForPage.decreasePage, newsScrollerForPage));

Three changes there:

  1. Using "click", not "onclick".

  2. Don't call your function, refer to it.

  3. Because I'm assuming that you want this within your decreasePage to refer to newsScrollerForPage, I'm using $.proxy to ask jQuery to make that happen for us. $.proxy accepts 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 (this value) during the call to the context provided.

Alternately, instead of $.proxy you can just use a closure directly:

$('#scroller-left-a').bind('click', function() {
    newsScrollerForPage.decreasePage();
});

That works because the anonymous function is a closure over the newsScrollerForPage symbol. 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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消