Search code examples
javascriptinline-code

How bad it is - Inline js calls with external handlers definition VS totally external js


I run into following code in my project:

html:

<input type="button" id="addmore" value="Add more" onclick="add_table(this)"/>

js:

function add_table(elem){
    var current_id = jQuery("table.t1:last").attr("id");

First I thought that this code is wrong and I must rewrite it to external code, i.e.

jQuery('#addmore)'.click(function add_table(elem){
    var current_id = jQuery("table.t1:last").attr("id");

But then I looked at it again and found that this html is more readable - I see which functions binds to which elements already in html, and I don't need to search it in js.

Of course it not encapsulated inside

jQuery(document).ready( 

so it will not work under some circumstances

So question: how bad this code is?


Solution

  • It's a question re-usability and personal taste. Inline code is more readable for very simple things like your example, but of course you are relying on add_table() being a global function - if you have hundreds of elements with different click handlers, you could end up with hundreds of functions/variables polluting the global namespace. And that's bad! :)

    In terms of re-usability, I find it better to code in distinct components that abstract functionality and can be called upon whenever needed - all within a defined (non-global) namespace.

    jQuery('#addmore)'.click(function add_table(elem) {
        var current_id = jQuery("table.t1:last").attr("id");
    }
    

    The code above gives a good separation of concerns - meaning the semantic information (HTML) is oblivious to the behavioural information (Javascript), which again helps create cleaner, more manageable code.