开发者

How to convert a javascript string to a javascript function, preserving the correct "this"?

A browser element has an onpopupshowing attribute, which is a string consisting of se开发者_JAVA百科veral javascript statements.

I want to "override" that bit of javascript.

Were this a function, I'd just assign it to a variable, assign my "overriding" function to the element attribute, and (if need be) call the original function from my overriding one, pretty much like this:

var oldfunc;
function myoverrridingfunc () { my statement; oldfunc(); my other statement; }

oldfunc = element.getAttribute( "onpopupshowing" )
element.setAttribute( "onpopupshowing", myoverrridingfunc );

but element.getAttribute( "onpopupshowing" ) isn't a function, it's a string.

I could use the Function object to turn the string into a function, but the string includes references to this. How do I preserve the right this?

What's the best way of intercepting/overriding this bit of script? Note: this only needs to work in Firefox, not in any version of java/ECMAscript.

Thanks.


var oldfuncStr = element.getAttribute("onpopupshowing");
element.removeAttribute("onpopupshowing");
var oldfunc = new Function(oldfuncStr);
element.addEventListener("popupshowing", function()
{
  myStatement;
  oldfunc.call(this);
  otherStatement;
}, false);

call is specifically for specifying this. I tested in Firefox, but with onclick event rather than onpopupshowing.


Perhaps you are overthinking this. Why not just wrap your JavaScript statements in quotes and assign it to the attribute? If the attribute expects JavaScript statements as a string, I wouldn't expect that assigning a function reference would even work anyway. (does it?)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜