4

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.

1
  • 1
    What is abc? It's a paremeter? Commented Sep 26, 2015 at 8:51

3 Answers 3

2

Try this:

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

var x = document.getElementById("someId").getAttribute('data-execute');
window[x].call();
Sign up to request clarification or add additional context in comments.

1 Comment

This will work, but without .abc at the end. Not sure should it be parameter, maybe?
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/

Comments

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");

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.