timpone timpone - 4 months ago 10
jQuery Question

how to namespace many events in a Javascript object literal

I am using jQuery events to capture events across a rails app. Basically, there are a set of event captures' on DOM elements that then call other functions. What I'd like to do is provide some namespacing to these event captures and an looking for the best way:

I currently have (but like 60 of them):

$(document).ready(function(){
$('.edit-item').on('click', arc.event_handler.edit_item);
});


and would like something like the following - basically provide the edit_item so we know where to look:

$(document).ready(function(){
var events.edit_item= {
$('.edit-item').on('click', arc.event_handler.edit_item);
};
});


But this is giving me an error. I am familiar with basic object literal syntax like:

var my = {
say_my_name: function(){
alert('my name');
}
}


but not sure how to apply it with jQuery functions. How would I do this?

I am aware that there are anonymous functions for namespacing this more agressively but, honestly, just want this one change right now

thx in advance

Answer

You seem to want

var events = {
    "edit_item": $('.edit-item').on('click', arc.event_handler.edit_item)
};

or

var events = {};
events.edit_item = …;
// equal to
events["edit_item"] = …; // Here you could use any expression (like a variable) 
                         // instead of the string literal

Now events.edit_item is the jQuery object returned by the expression.

Comments