动态调用功能取决于名称



,所以我有一个原型对象,该对象注册了事件侦听器。侦听器接收一个对象和一个指示发射事件源的字符串。该对象将是某些函数调用的参数(_convertToX(someObj)_convertToY(someObj),...)。
现在,我要做的是动态调用我的convert函数(将来可能会增加一些),每个函数都会完全使用一个参数(someObj)。

// constructor
const MyFactory = function () {
    // ...
    $rootScope.$on('someObj:changed', (event, someObj, source) => {
        // TODO: call converters dynamically, but not the one which converts back to the source
        // source can be 'X', 'Y' or 'Z'
    });
}
MyFactory.prototype._convertToX = function (someObj) {
    // TODO: convert to X and emit
};
MyFactory.prototype._convertToY = function (someObj) {
    // TODO: convert to Y and emit
};
MyFactory.prototype._convertToZ = function (someObj) {
    // TODO: convert to Z and emit
};

可能已经有类似问题的答案,但我不知道如何找到正确的搜索词...

我的方法是创建一个具有所有converter功能的数组,然后从数组中调用它们。我看到的问题是如何确保不调用转换回source的转换器?

/**
 * Hold references to all converters.
 * @type {Array<function>}
 */
this._converters = [
    this._convertToX,
    this._convertToY,
    this._convertToZ
];
// assume source is 'Z'
$rootScope.$on('someObj:changed', (event, someObj, source) => {
    // how to call each function in this._converters with someObj as argument
    // except this._convertToZ(someObj) ?
});

这是一种干净的方法吗?如何做?
还是有一种更清洁/更简单的方法来实现此问题?

您可以使用括号符号来访问基于 string的字符串

的函数
const MyFactory = function () {
    //Store the reference to a variable
    const self = this;
    $rootScope.$on('someObj:changed', (event, someObj, source) => {
        //Use Bracket notation to access the function
        self["_convertTo" + source](someObj)
    });
}

根据评论,除源外,我建议您创建sources的列表,然后在事件处理程序中获取除源外的所有方法并执行它们。

const MyFactory = function () {
    //Store the reference to a variable
    const self = this;
    const sources = ['X', 'Y', 'Z'];
    $rootScope.$on('someObj:changed', (event, someObj, source) => {
        //Use Bracket notation to access the function
        var expectSource = sources.filter(x => x !== source);
        expectSource.forEach(x => self["_convertTo" + x](someObj))          
    });
}

最新更新