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

2
  • If I understand you correctly you could use eval($j(this).attr("data-callback")) Is that what you needed? Commented Feb 10, 2012 at 13:19
  • stackoverflow.com/questions/11165707/… Commented Feb 18, 2016 at 8:55

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

2 Comments

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'));
This is almost the same. See this for example
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]();
  // ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.