views:

92

answers:

2

I have two events that I want to observe on an object,

input.blur(function(event) {
  ajaxSubmit(this);
  event.preventDefault();
});

form.submit(function(event) {
  ajaxSubmit(this);
  event.preventDefault();
});

But I feel like this isn't dry enough, can I bind two events to my object input and execute my function ajaxSubmit() if either fire?


What would be super cool is if you could do:

input.bind("blur", "submit", function(event) {
  ajaxSubmit(this);
  event.preventDefault();
});
+3  A: 

Yes, just declare the function and then bind it to the events:

var ajaxCallback = function(event){
  ajaxSubmit(this);
  event.preventDefault();
};

input.blur(ajaxCallback);
form.submit(ajaxCallback);

Note about variable declaration:

As @cletus points out, the way I declare the function provides a variable that is private to whichever scope it is defined in. I always program this way to minimize polluting the global namespace. However, if you are not defining both this callback and binding it to the elements in the same block of code, you should define it this way:

function ajaxCallback(event){ ... }

That way it is available wherever you later bind it using the .blur and .submit methods.

Doug Neiner
You're better off defining the function: function ajaxCallback() { ... }. Your way could have the variable undefined when you try and use it whereas a straight function definition doesn't have that problem.
cletus
@cletus I wrote it that way intentionally, but you have a good point that the difference may not immediately be apparent to those reading my answer. I updated it to provide some explanation around the options of declaring the function. Thanks!
Doug Neiner
@Doug Neiner: You bound the handler *after* the function expression, so your code is fine. Both expressions define the function in whatever scope the code is in.
Crescent Fresh
@Crescent Fresh, The difference could cause a problem if the function declaration and the binding calls were in separate `$(function(){ ... })` blocks for some reason, or were in separate files wrapped in a closure.
Doug Neiner
+3  A: 

You can use the bind method

$("#yourinput").bind("blur submit", functionname);

Can combine any number of events; separate them with a space.

rahul
Of course this would not work since input fields do not have `submit` events, but the concept is sound for binding multiple events.
Doug Neiner
He can wire any events inside the bind function.
rahul
@adamantium, sorry I was unclear. The code would not throw an error, but the `submit` event would not be called on `form` submit as seems to be the OP's intention.
Doug Neiner
+1 You learn something new every day.
cletus
Hey you actually answered my question, even though I asked it like a dork and it didn’t even make any sense, thanks guys!
Joseph Silvashy