Let’s say I have a div with two anchors:
<div id="#dialog">
<a href="#" class="ok">Delete</a>
<a href="#" class="cancel">Cancel</a>
</div>
In order to make the <a> anchors work, I’m using the following two calls:
$('#dialog a.ok').click(function() {
$.ajax({ ... });
$(this).closest('#dialog').dialog('close');
});
$('#dialog a.cancel').click(function() {
$(this).closest('#dialog').dialog('close');
});
I’d like to be able to combine it to something like this instead:
$('#dialog').execute(function() {
var dialog = $(this);
dialog.find('a.ok').click(function() {
$.ajax({ ... });
dialog.dialog('close');
});
dialog.find('a.cancel').click(function() {
dialog.dialog('close');
});
});
The fake exeucte() function will execute the anonymous function immediately, without binding it to a DOM event. I’d like to use this pattern in order to group related functions together (in this case, a dialog has two buttons that are very closely related to each other).
My question is twofold:
- What is the actual jQuery call I should be using here?
- Is this the best way of grouping related functions together?
You don’t need any special jQuery stuff for this, just write a function and give it
$('#dialog')as an argument:Or, if you really have a thing for anonymous functions, you could use
each:but using
eachwith a selector that can only match a single element looks funny. You could also define your own self-executing function:There is no best here, you use what fits your particular circumstances and local conventions.