Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript call back by function name in data attribute

I am trying to provide a call back function for an ajax call, where the function name is saved under the "data-apply" attribute of a form.

jQuery(function($) {
    $('form[data-async]').on('submit', function(event) {
        var $form = $(this);
        var $target = $($form.attr('data-target'));
        var apply = $form.attr('data-apply');
        $.ajax({
            type: $form.attr('method'),
            url: $form.attr('action'),
            data: $form.serialize(),

            success: function(data, status) {
                var callBackFunc = new Function(apply);
                callBackFunc.call();
            }
        });

        event.preventDefault();
    });
});

function addBubble(){
    alert('a');
}

The form:

<form id="111" class="form-horizontal " data-async data-target="#rating-modal" data-apply="addBubble();"  action="/some/action/performed" method="POST">

I want to avoid using eval() in this case, since eval() might introduce security and performance issues. Not sure Function() is a safer method or there is a completely different way to handle this.

So is there anyway to pass in a function callback in order to handle difference situations?

The original code was borrowed from: https://gist.github.com/havvg/3226804

like image 757
Egg_Egg Avatar asked Sep 28 '15 15:09

Egg_Egg


2 Answers

Since the function is globally defined, you can call it through the window object.

window["functionName"].call();

Remove the parentheses from addBubble

<form id="111" class="form-horizontal " data-async data-target="#rating-modal" data-apply="addBubble"  action="/some/action/performed" method="POST">

Javascript

jQuery(function($) {
    $('form[data-async]').on('submit', function(event) {
        var $form = $(this);
        var $target = $($form.attr('data-target'));
        var apply = $form.attr('data-apply');
        $.ajax({
            type: $form.attr('method'),
            url: $form.attr('action'),
            data: $form.serialize(),

            success: function(data, status) {
                if(typeof window[apply] == "function")
                    window[apply].call(); //window[apply](); or window[apply].apply(); will work too
            }
        });

        event.preventDefault();
    });
});

function addBubble(){
    alert('a');
}
like image 151
Marcos Casagrande Avatar answered Sep 17 '22 20:09

Marcos Casagrande


If the function is defined globally (i.e. on the window object) you could use window[$form.attr('data-apply')]() to call the callback. Note that you would have to remove the () in data-apply

like image 26
arcyqwerty Avatar answered Sep 20 '22 20:09

arcyqwerty