3

I have created a DOM structure like this

<div data-execute="someFunction.abc" id="someId">
  </div>

I am able to retrive the attribute in js but I intend to execute this as a callback function. So I am doing like this

var x = document.getElementById("someId").getAttribute('data-execute');

As expected this is returning someFunction.abc .But on consoling typeof(x) it is showing "string".Please refer to this fiddle

var someFunction = function() {
  alert("Hello")
}
var load = (function(module, global) {
  var x = document.getElementById("someId").getAttribute('data-execute');
  console.log(typeof(x))

}(load || {}, this))
<div data-execute="someFunction.abc" id="someId">
  Some Function
</div>

I also checked this link Passing a Javascript function through inline data- attributes

But no way I am able to execute it as a call back function.Any help will be truly appreciable.

brk
  • 48,835
  • 10
  • 56
  • 78

3 Answers3

2

Try this:

<div data-execute="someFunction.abc" id="someId"></div>

var x = document.getElementById("someId").getAttribute('data-execute');
window[x].call();
slash197
  • 9,028
  • 6
  • 41
  • 70
2

You can use the call methodon the function defined in the global scope, you can access it in the global window ojbect.

Ref:

The call() method calls a function with a given this value and arguments provided individually.

I have assumed the code after the point is a paramter to pass to the function.

Code:

var someFunction = function (p) {
    alert(p)
}
var load = (function (module, global) {
    var x = document.getElementById("someId").getAttribute('data-execute');
    window[x.split('.')[0]].call(undefined, x.split('.')[1]);

}(load || {}, this))

Demo: https://jsfiddle.net/IrvinDominin/5bjsmu3x/

Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111
0

I was struggling with the same question and I found this solution :

HTML :

<element data-call="return alert('callback');">

JS :

Function(YourElement.getAttribute('data-callback'))();

You can store it in a variable and add parameters too :

HTML :

<element data-call="return str.toUpperCase();">

JS :

var fn = Function("str", YourElement.getAttribute('data-callback'));
var returned = fn("Test String");
Poupoudoum
  • 31
  • 4