如何正确设置动态XUL元素的事件? [英] How to properly set events for dynamic XUL elements?
问题描述
我有一个工具栏扩展,可以生成动态的 toolbarbutton
和 menuitem
元素。这些项目通常是这样构造的:
tempMenuItem = document.createElement(menuitem);
tempMenuItem.setAttribute(label,Some Label);
tempMenuItem.setAttribute(tooltiptext,Some Tooltip);
tempMenuItem.setAttribute(oncommand,myObject.someFunction());
这段代码工作的很好,但是当我把我的扩展提交给官方的add -on repository:
使用setAttribute设置*属性
警告:为了防止漏洞,应该总是使用addEventListener来定义事件处理程序(如'onclick'和'onhover')。
为这些动态元素设置适当的命令处理程序?我知道这只是一个警告,但作为我这个强迫性的程序员,我想尽可能以最干净的方式来做事。有没有更好的方法来做到这一点?
那么你显然使用 addEventListener()
方法的建议说: p>
tempMenuItem.addEventListener(command,function(event)
{
myObject.someFunction();
},false);
如果您还使用 Function.bind()
p>
tempMenuItem.addEventListener(command,myObject.someFunction.bind(myObject),false);
I have a toolbar extension that generates dynamic toolbarbutton
and menuitem
elements. These items are typically constructed like this:
tempMenuItem = document.createElement("menuitem");
tempMenuItem.setAttribute("label", "Some Label");
tempMenuItem.setAttribute("tooltiptext", "Some Tooltip");
tempMenuItem.setAttribute("oncommand", "myObject.someFunction()");
This code works just fine, but I get the following warning when I submit my extension to the official add-on repository:
on* attribute being set using setAttribute
Warning: To prevent vulnerabilities, event handlers (like 'onclick' and 'onhover') should always be defined using addEventListener.
How else can I set the appropriate command handler for these dynamic elements? I know this is simply a warning, but being the obsessive compulsive programmer that I am, I'd like to do things in the cleanest way possible. Is there a better way to do this?
Well, you obviously use addEventListener()
method as the suggestion says:
tempMenuItem.addEventListener("command", function(event)
{
myObject.someFunction();
}, false);
Or somewhat shorter if you also use the Function.bind()
method:
tempMenuItem.addEventListener("command", myObject.someFunction.bind(myObject), false);
这篇关于如何正确设置动态XUL元素的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!