【发布时间】:2017-09-11 10:15:06
【问题描述】:
我(我正在尝试使用通用方法来解析 dom 元素并将事件监听器附加到它们。
所以我添加了一个html5数据属性来指定触发事件时应该调用的方法。
我正在寻找的是一种通过她的字符串值调用类内部方法的方法:
static addEvent(element, trigger, action)
{
element.on(trigger, action);
}
其中element是附加eventListener的dom元素,trigger是监听器的类型,action是我们应该在这个类中调用的方法(这里我要调用toggleFullscreen)。
有没有办法做到这一点?
编辑:需要避免eval解决方案,我用this[action]做了一个测试,但这不是例外结果。
这是我的代码
dom 元素:
<div class="interface">
<span class="home_common-fullscreen action fa fa-desktop" data-action="toggleFullscreen" aria-hidden="true"></span>
</div>
javascript函数:
class Interface {
constructor() {
this.domElements = jQuery(".interface");
this.attachAction();
}
attachAction()
{
let fullScreenButtonElement = this.domElements.find(".action");
if(fullScreenButtonElement !== undefined)
{
if(Array.isArray(fullScreenButtonElement))
{
jQuery(fullScreenButtonElement).each(function()
{
Interface.parseAction(this);
});
}
else
{
Interface.parseAction(fullScreenButtonElement);
}
}
}
static parseAction(element)
{
let action = element.attr("data-action");
if(action === undefined)
{
throw new InterfaceError("Trying to parse action element without defined data-action attribut");
}
let trigger = typeof element.attr("data-trigger") !== 'undefined' ? element.attr("data-trigger") : "click";
try
{
Interface.addEvent(element, trigger, action);
}
catch(err)
{
console.log(action + "not found in Interface")
}
}
static addEvent(element, trigger, action)
{
element.on(trigger, action);
}
toggleFullscreen()
{
alert("foo");
}
}
【问题讨论】:
-
你在哪里实例化
Interface?您在哪里尝试使用括号表示法?它应该工作
标签: javascript jquery ecmascript-6