JaggyGauran

Freelance developer, and designer

Lazy Javascript Event Bindings

Okay, I've been doing a few projects and I'm pretty lazy at binding click and keyboard events. Here's just a quick, hack to make things work.

Disclaimer

Take note, I am not a javascript expert! Soooo, this may be not the best practice. is not the best practice (Though, if by any off chance that it's useful, I'd love to know).

I use this for mostly prototyping and quick functionality tests and refactor them later. Though, if I see no other downsides(see below), I might stick to using this.

Some code...

<!-- html -->
<a href="#" data-model="Table" data-action="add_row" data-param="">Add row</a>
<a href="#" data-model="Table" data-action="delete_row" data-param='{"id": 1}'>Add row</a>
var Table = {
   
    add_row: function (self) {
        console.error('adding row');
    },
    

    delete_row: function (self, params) {
        console.error('deleting row');
        
        var element = $(self);
        var id = params.id;
    }
};

$(document).on('click', '[data-trigger="click"]', function (event) {
    event.preventDefault();

    var $elem  = $(this);
    var model  = $elem.attr('data-model');
    var action = $elem.attr('data-action');
    var params = $elem.attr('data-params');

    if (typeof params != 'undefined' && params != '') {
        params = JSON.parse(params);
    }

    window[model][action](this, params);
});

I'm still trying to find a way to pass parameters like adding a data-params='{"some":string}' then just unserialze on the click event but for now I still have no case to use it from.

Downside Variable Scope

It solves most of my binding issues but, I hate that I can't find a way to fix the scope for this which is kind of a bummer.

It looks like it's a good way to pass this and use the data-params attribute.

Anyways, let me know what you think! Tweet me at @jaggygauran