Cameron
Cameron

Reputation: 28793

Call function using passed data attributes

I have a form like:

<form data-controller="Posts" data-method="admin_add">

And then I want to call a function based on these passed data attributes when the form is submitted.

$(document).on('submit', 'form', function(e){

    e.preventDefault(); // there is no server so nothing to submit to

    var formData = $(this).serialize();

    var controller = $(this).attr('data-controller');
    var method = $(this).attr('data-method');
    // I use .attr instead of .data because .data is funny sometimes

    var fnString = controller + '.' + method;
    var fn = window[fnString];

    if (typeof fn === "function") fn(formData);

});

This is based on what I've read here: http://www.sitepoint.com/call-javascript-function-string-without-using-eval/

And it should of called:

Posts.admin_add(formData);

But it doesn't call the function... and if I remove the if statement then I get an error that it's not a function... Any ideas?

Upvotes: 0

Views: 196

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

Remember, you are using square brackets to avoid using eval:

var fn = window[controller][method];
fn(formData);

Upvotes: 7

Related Questions