ES6按字符串值调用类方法

时间:2017-09-11 10:15:07

标签: javascript jquery ecmascript-6

我(我试图使用泛型方法来解析dom元素并将事件侦听器附加到它们。

所以我添加一个html5数据属性来指定触发事件时应该调用的方法。

我正在寻找的是一种通过字符串值调用类中方法的方法:

static addEvent(element, trigger, action)
{
    element.on(trigger, action);
}

其中element是附加eventListener的dom元素,trigger是侦听器的类型,action是我们应该在这个类中调用的方法(这里我想调用toggleFullscreen)。

有办法吗?

编辑:需要避免eval解决方案,我使用此[操作]进行了测试,但这不是例外结果。

这是我的代码

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

JSFiddle

2 个答案:

答案 0 :(得分:2)

class Interface {
    // This method is a property of the class itself
    static addEvent(element,trigger,action) {
        element.on(trigger,Interface[action]);
    }

    // May need to be static if you don't plan on creating objects
    static toggleFullscreen() {
        console.log("It Works");
    }
}

// Or the Event Handler could be in another object
class EventHandlers {

    // It'd be accessed with EventHandlers["toggleFullscreen"];
    static toggleFullscreen() {

    }
}

// Or make it a global function
// Which would be accessed with window["toggleFullscreen"];
function toggleFullscreen() {

}

答案 1 :(得分:0)

你需要这样的东西:

class XClass {
  f2() {
    console.log("Message from f2");
  }

  f4() {
    eval("this.f2()");
  }
}

但我认为静态不适用于这种方法。

相关问题