mojuba
mojuba

Reputation: 12227

JavaScript eval() with `this`

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

Upvotes: 2

Views: 1551

Answers (4)

rsp
rsp

Reputation: 111404

A more elegant solution would be to use custom events, bind handlers to some custom events on your HTML elements and trigger them in some other parts of your code. See this tutorial and the answer by Sidharth Mudgal for some examples.

Upvotes: 0

Anoop
Anoop

Reputation: 23208

Instead of using this you can use elem.

 <div id=myElem onMyUpdate="alert('Update called for ' + elem.id)">...

js:

if (elem.hasAttribute('onMyUpdate')){ // all variable available here will be available inside eval.
     eval( elem.getAttribute('onMyUpdate') );
}

Upvotes: 0

Andreas Grech
Andreas Grech

Reputation: 107980

Ideally, you should do this completely unobtrusively, and without the use of eval:

<div id="myElem"></div>

.

var elem = document.getElementById('myElem');
elem.onMyUpdate = function () {
    alert(this.id);
};

// ...

elem.onMyUpdate && elem.onMyUpdate();

Upvotes: 1

geocar
geocar

Reputation: 9305

How about this:

if(elem.hasAttribute('onMyUpdate')) {
  var fun = new Function(elem.getAttribute('onMyUpdate'));
  fun.call(elem);
}

Upvotes: 2

Related Questions