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 certain events happen in my form like so:
$('#country-select').bind('change', function() {
Form.updateCurrency();
});
$("input[type='checkbox']").bind('change', function() {
Form.handleCheckBox();
});
I have a lot of these event listeners, and frankly, I find them ugly listed out one by one like that and not tied directly to the object they relate to. Is there a more elegant way of encapsulating them within my object literal Form? Is there a best practice?
I like
@gillescanswer, it’s on the right tracks.However, I think we can do better.
The main issue with
@gillescanswer is that its missing the dynamic aspect of things (event handlers for instance), also it forces your to define ugly callback functions.So heres how I think you should solve your problem.
How would it all work? Thats easy! We just need to call
testObj.registerHandlers().JSFiddle demo