I’ve been reading about custom events in jQuery and why they should be used but I’m still clearly missing the point. There is a very good article I read here that has the following code example;
function UpdateOutput() {
var name = $('#txtName').val();
var address = $('#txtAddress').val();
var city = $('#txtCity').val();
$('#output').html(name + ' ' + address + ' ' + city);
}
$(document).bind('NAME_CHANGE ADDRESS_CHANGE CITY_CHANGE', function() {
UpdateOutput();
});
$('#txtAddress').keyup(function() {
$(document).trigger('ADDRESS_CHANGE');
});
$('#txtCity').keyup(function() {
$(document).trigger('CITY_CHANGE');
});
Can someone tell me why I just don’t call the UpdateOutput() function directly? It would still work exactly the same way, i.e.
$('#txtAddress').keyup(function() {
UpdateOutput()
});
$('#txtCity').keyup(function() {
UpdateOutput()
});
Many thanks
Because you are one client of that event, even though you have full control over the entire application. It helps decoupling your code better.
As one of the clients who is interested in knowing when the name, address, or city changes, you are updating the values in some part of the screen. Some other client might want to do something else such as pull up all adjacent cities, reverse geocode the address, do a name lookup on namesdatabase.com, and so on.
You can still control everything without events and call multiple functions directly or put everything in it’s own function, but adding events decouples the implementation from what needs to be done, based only on the type of event, so
UpdateOutputdoes not have to worry about pulling up names from a names database, and you don’t have to worry about calling all the necessary functions yourself whenever a particular event happens as long as there is a basic understanding of the events defined in the system and what they represent.A second reason is abstraction. For example, deleting of a user account might get triggered by a simple click, but just by translating that to a higher level event such as
DeleteAccount, things would get simpler and understandable when you consider that there could be tens, or hundreds, or maybe even thousands of such events all across the application. Working at a higher level of abstraction than “keyups”, “keydowns”, “mouseovers”, etc. (which are really meaningless anyways in the context of an application and the intent behind), things can get a lot more manageable as the application size grows.