SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    Guru in training bronze trophy SoulScratch's Avatar
    Join Date
    Apr 2006
    Location
    Maryland
    Posts
    1,838
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Explanation needed (is this a bind?)

    Alright. We all know the proper w3 method to register event listeners is

    el.addEventListener(ev, fn, capture)

    So say you wanted to attach this function to the window's load event

    function changeBackground(el, color) {
    el.style.backgroundColor = color;
    }

    window.addEventListener('load', changeBackground(window, 'red'), false);

    This would of course give you some weird error if you have a decent modern browser, complaining about arguments

    Anyway, I know that the way to get it to work would be to wrap it in an anonymous function..

    window.addEventListener('load', function() {
    changeBackground(window, 'red');
    }, false);

    I think some frameworks/libraries use a custom function called bind to do the same thing... which adds the anonymous function for you so there's less typing involved. Could anyone explain the technicalities of why the anonymous function is necessary? And how custom bind functions do it?

    Thanks.

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Because in this expression-
    window.addEventListener('load', changeBackground(window, 'red'), false);
    You are not passing a function, but the return value of the function-
    undefined, in this case.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •