Search code examples
javascriptdom-eventslate-binding

Are there any cases where you have to use early-binding/inline event attribute in HTML/JavaScript


In my answer to the following SO question: What does event binding mean?, I made a passing remark that the use of inline-JavaScript/Early-Binding to bind JavaScript Events was 'often misguided'

For example:

<input id="MyButton" type="button" value="clickme" onlick="Somefunction()" />

I was arguing for the 'late-binding' approach where there is no JavaScript referenced in the markup, which I understand to be established best-practice. However, the commenters asserted that there were occasions that necessitated its use, and I wondered what these might be.

Without engaging in a discussion on the relative merits of either, can anyone think of any circumstances that dictate that you use the (e.g.) onclick attribute over a late-binding approach.


Solution

  • I think many developers will do this either due to ignorance or lack of knowledge (which is, of course, common) and the remaining developers will do it because it's simply more convenient to use HTML-JS attributes than late binding, if you know that certain objects and functions are always loaded on every page and they will simply 'be there'.

    I think this is especially true when said HTML comes from an AJAX callback. Take an example where an AJAX request comes back with an HTML response and that HTML is inserted into the page. Now the naive developer would think along these lines:

    • I have no idea what elements are inside that response HTML so I don't know what late bindings I need to add.
    • Perhaps I need to add them all just in case! Or write some parsing script that detects elements and binds to the ones I find?
    • But what if I need to bind to something that doesn't already exist? Time to write some long inline JavaScript!

    All of this can be eliminated by using a kind of omnipresent binding that applies to all current and future elements on the page. In jQuery, the equivalent is live(). Instead of writing:

    $('.foo').click(function(){...});
    

    You could write:

    $('.foo').live('click', function(){...});
    

    Now, all elements with class name 'foo' will execute the function when clicked, including elements that don't currently exist. Very useful for dynamic AJAX interfaces.

    You may know that already, but I'm just pointing out that anything JS attributes can do, pure JS can do better, and I'd consider that best practise.