How to properly set events for dynamic XUL elements?

戏子无情 提交于 2019-12-12 05:09:02

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/13371105/how-to-properly-set-events-for-dynamic-xul-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!