1

I have setup some automatic form submission code. Basically when a form is submitted javascript takes care of it, finding all inputs and such, and sending the data via ajax to the action attr of the form.

$j('body').delegate('form', 'submit', function(e) {
    e.preventDefault();
    if($j(this).prop('data-callback', true))
        asf.forms.processForm($j(this).attr('name'), $j(this).attr('data-callback'));
    else
        asf.forms.processForm($j(this).attr('name'));
});

But i need to include callbacks. I need to make the code global so i cant code any specifics for each form. So i thought of adding an attribute with the callback function name like so:

<form action="" method="" data-callback="posts.addPost()">

The problem is I dont know how to fire that function inside javascript. Any ideas? I cant use onsubmit because i need access to all of the forms information which means doing this callback within the ajax response.

Thanks

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81

2 Answers2

10

I know that eval is evil, but it seems only reasonable solution:

eval($(form).attr('data-callback'));

If you put only method name in data-callback attribute (eg. data-callback="posts.addPost") it's possible to call it without eval:

var methodName = $(form).attr('data-callback');
var parts = methodName.split('.');
var method = window;

$(parts).each(function(){
    method = method[this];
});

method();
Krzysztof
  • 15,900
  • 2
  • 46
  • 76
  • not only solution :) i've made it that way: function run(code) { var res = new Function('return ' + code + '|| false'); return res(); } run($(form).attr('data-callback')); – Sergei Zahharenko Jan 17 '13 at 12:30
  • This is almost the same. See [this](http://stackoverflow.com/questions/4183591/new-function-with-variable-parameters) for example – Krzysztof Jan 17 '13 at 12:47
2

To achieve this without resorting to eval, I suggest you store all your "form callbacks" in an object, like so:

var formCallbacks = {
  'posts.addPost': function() {
    // ...
  },
  // ...
};

Using your data-callback mechanism, you would look up the callback in the response handler:

function(args, callbackName) {
  formCallbacks[callbackName]();
  // ...
}
Linus Thiel
  • 38,647
  • 9
  • 109
  • 104