使用_.without删除项目

时间:2015-05-19 11:05:12

标签: javascript typescript underscore.js

我正在数组中实现切换功能 切换代码如下:注意:代码是TypeScript 我传递toggleMode(模式)时如何删除项目// mode = 1(整数) 当我这样做时,它会进入disableMode并执行省略或不执行但我猜不行。

private toggleMode(mode:ConversationMode)
{
    mode = parseInt(mode.toString());
    var modeEnabledCurrently =this.getRuleByMode(mode);

    if (!modeEnabledCurrently)
        this.enableMode(mode);
    else
        this.disableMode(mode);
}

按代码获取规则:

getRuleByMode(mode:ConversationMode)
{
    return _.findWhere(this.modes, selfjs.createSimpleObject("ConversationMode", mode));
}

启用和禁用代码:

enableMode(mode:ConversationMode) { 
var obj = selfjs.createSimpleObject(ScheduleRule.COL_CONVERSATION_MODE, mode);
        this.modes.push(obj); 
}

disableMode(mode:ConversationMode) { 
this.modes = _.without(this.modes, mode); 
//this.modes = _.omit(this.modes, function(mode, key, object) {
            return _.findWhere(this.modes, selfjs.createSimpleObject(ScheduleRule.COL_CONVERSATION_MODE, mode));
        });
}

当我添加它时显示:

modes: Array[2]
  0: undefined
  1: Object
     conversation_mode: 1

请指导。

1 个答案:

答案 0 :(得分:0)

我深入挖掘并发现_.findwhere只能使用键值对,而_.without使用数组而不是对象,所以将_.findWhere更改为_.where并使用_.without

enableMode = function (mode) {
        this.modes.push(mode);
};

disableMode = function (mode) {
        this.modes = _.without(this.modes, mode);
};

getRuleByMode = function (mode) {
        return _.where(this.modes, mode);
};