Say I have some actions binded to a link ( with .click or .live), and I want to do the same thing later, but I don’t want duplicated code. Which is the correct way and why?
This:
$('#link').click(function(){
//do stuff
});
//called later
$('#link').trigger('click');
OR:
$('#link').click(function(){
do_stuff();
});
//called later
do_stuff();
//defined here
function do_stuff(){
//do stuff
}
Actually, you only need to distinguish between whether or not you’re accessing the
event objectwithin the event handler. Another difference is that the context of that invoked handler might change, sothiswon’t point to the invokednodewhen called directly.If you’re accessing
thisor theevent object, you indeed should use.triggerto execute the handler. You could also pass in all necesarry data yourself by manually invoking the method, but why invent the wheel.Otherwise, you’re just fine in directly calling that function from wherever you have access to it.