JavaScript eval() with `this`
- by mojuba
If I define a JavaScript code snippet in my HTML, like so:
<div id=myElem onMyUpdate="alert('Update called for ' + this.id)">...
then what is the most elegant way of evaluating it from within JavaScript with this properly assigned?
What I came up with so far is something like this:
if (elem.hasAttribute('onMyUpdate'))
(function () { eval(elem.getAttribute('onMyUpdate')) }).call(elem);
which looks terrible (to me), but works. Any better/more elegant alternatives?
MDN says there used to be the second argument to eval() for doing just that but it's deprecated now; MDN then suggests to use operator with() instead, which, if you follow the link provided, turns out to be made deprecated by the latest standard. Dead end, in other words.
(As a side note, StackOverflow ignores the word this in search terms and thus it may miss relevant answers - is there a way of telling it not to?)
Edit: I forgot to mention: no jQuery please, just vanilla JavaScript