Object literals and event listeners, best practice?

Suppose I have an object with some properties and methods:

var Form = { name: 'sign-up', show: function() {...}, hide: function() {...}, validate: function() {...}, updateCurrency: function() {...}, handleCheckBox: function() {...} } 

Now I want to call different methods when the following events occur in my form:

 $('#country-select').bind('change', function() { Form.updateCurrency(); }); $("input[type='checkbox']").bind('change', function() { Form.handleCheckBox(); }); 

I have many of these event listeners, and to be honest, I find them ugly, being listed one by one and not attached directly to the object to which they belong. Is there a more elegant way to encapsulate them in my Form object literal? Is there any best practice?

+7
source share
3 answers

I like @gillesc answer, it's on the right tracks. However, I think we can do better.

The main problem with @gillesc 's answer is that there is no dynamic aspect of things (like event handlers), and also forces you to define ugly callback functions.

So, as I think, you should solve your problem.

 // Test object var testObj = { // Our event handlers. // Notice how we must only define the callback function name here. // Not the function itself. The callback function must be defined in testObj. handlers: { '#form submit': 'onSubmit' }, // Method that will register all handlers to some selector registerHandlers: function() { var that = this; // Go through the handlers list. $.each(this.handlers, function(k, v) { // Parsing the event to two different parts. // 1. trigger event // 2. selector var split = k.split(" "), el = split[0], trigger = split[1]; // Delegating the trigger to selector $(document).delegate(el, trigger, that[v]); }); }, // Our actual callback function onSubmit: function(evt) { evt.preventDefault(); alert("submit"); } }; 

How will all this work? It is easy! We just need to call testObj.registerHandlers() .

Jsfiddle demo

+6
source

Organize your markup better and add classes to the element that matches the methods of the event handler so you can easily create a list of handlers and iterate over them to bind them to the target elements.

 Var Form = { ...., handlers: { country: function() {}, checkbox: function() {} } }; $.each(FORMS.handlers, function(k, v) { $('.' + k).on('change', v); }); <select class="country">....</select> <input class="checkbox" type="checkbox" /> 

Then all you have to do is add classes and handlers to extend

+3
source

Well, you don't need to wrap your functions as part of more functions to get you started. You cannot just:

 $('#country-select').bind('change', Form.updateCurrency); $("input[type='checkbox']").bind('change', Form.handleCheckBox); 
0
source

All Articles