Question

Given an element:

<div id='adiv' customAttr='myFuncToExecute'></div>

What would be the best way to read the custom attribute, and convert it into an executable method in JavaScript. I am currently using the new Function() constructor:

if ($('#adiv').attr('customAttr')) {
    var myFuncV1 = new Function('return ' + $('#adiv').attr('customAttr') + '()');
    var myFuncV2 = new Function($('#adiv').attr('customAttr'));
}

myFuncV1 would be executable as myFuncV1(). Alternatively, I am able to use myFuncV2 in event handler bindings:

$('#adifferentdiv').click(myFuncV2);

This does work for what I need, but using the new Function() constructor is equivalent to using eval().

The Question: Is there a better approach to take for reading and evaluating (no pun intended) custom attributes that contain the name of methods that are to be used elsewhere in a script?

Thanks in advance for the help.

Was it helpful?

Solution

Make the methods properties of an object, then you can remove the new Function approach:

var obj = {someMethod: function(){...}};

obj[$('#adiv').attr('customAttr')](); 

though you might want to test that obj[$('#adiv').attr('customAttr')] exists before calling it, e.g.

var fn = obj[$('#adiv').attr('customAttr')];

if (fn) fn();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top