tags:

views:

31

answers:

1

Is there any way using jQuery's .bind() and .trigger() calls to execute a user defined function (ex: save ()) and act upon the return from the method? For example:

$("#aForm").bind ('save', function () {
  return true;
});

and then:

if ($("#aForm").trigger ('save') == true) {
  doSomething ();
}
+2  A: 

Why don't you act on the return value in the callback itself? It takes away the extra check (that won't work like you would expect it to).

$("#aForm").bind ('save', function () {
  if(some stuff happens that is true) {
      doSomething();
  }

  else {
      doSomethingElse();
  }
});

Callbacks don't work synchronously. They are used to handle things that happen asynchronously (like events). In they context of callbacks, they are pieces of code that run when something happens. Returning values from them really doesn't make sense. In your example, since you want to check on the return value of the callback, you can be sure that you only get a return value when the callback runs (because you're trying to use them like a regular function). In that case, put that logic inside the callback itself (like I have shown above).

Vivin Paliath
I'm trying to avoid doing that for the simple reason that I have multiple forms in a dialog (each in a separate tab). I'd like the dialog itself to handle actually calling each form's "save" method individually based on a "dirty" flag. That's why I'm trying to abstract out the "doSomething()" and "doSomethingElse()" functions from the forms -- i.e. the main dialog handles the overall flow. I just want each of the forms to handle saving their data -- or returning false if an error occurs when saving their data. Is it possible to add a custom "save" function to each form using .extend()?
Dave
Why don't you have a validation method that handles validation. You should bind to your form's `submit` event and then run the validation. If the validation is successful, then submit the form.
Vivin Paliath
Along that same vein, wouldn't it be possible for me to add a new function called 'save' or 'saveData' just like the validation plugin does to add a new capability to the form, and then use that method to save the data? I've not made a plugin, but this seems the more elegant way to achieve what I was trying to do, no?
Dave
Sure, you can do that if you need to perform an AJAX request of some sort (or need to modify the data). But in general if you have bound to the `submit` event, you just need to return the result of the validation. The submit event is special in the sense that it inspects the return value of the handler to see if it needs to submit the form.
Vivin Paliath