Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function inside a custom data-attr?

Given a current CMS we are working in, I need to call functions within a custom data-attribute. Is it possible to call the contents of a data attribute as a function to run like below? Simple example:

Set

 <button data-function="alert('hello world')">Run Function</button>

Run

$('button').attr('function');

I believe the above is just getting the contents and not actually executing anything when written.

Is this possible?

like image 315
Myoji Avatar asked Feb 12 '23 01:02

Myoji


2 Answers

You could create a Function from the data attribute:

// create
var funcStr = $('button').data('function');
var f = new Function(funcStr);

// invoke
f();

See MDN

like image 66
haim770 Avatar answered Feb 13 '23 15:02

haim770


This is another approach if the function is known.

     $(document).ready(function() {
       $('button').click(function() {
         var functionObject = JSON.parse($('button').attr('data-function'));
         window[functionObject.name].apply(window, functionObject.arguments);
       });
     });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button data-function='{"name": "alert", "arguments" : ["hello world"]}'>Run Function</button>

It parses the JSON string from the data-function attribute. Call the function provided by name using the window object (eliminating eval) and passes the arguments (inside an array) to the function using apply.

like image 35
Mouser Avatar answered Feb 13 '23 14:02

Mouser