Javascript pattern: Conditional event handler

前端 未结 5 356
轮回少年
轮回少年 2021-01-27 03:29

Given e.g. a class instance of some sort has a state (e.g. \'active\', \'inactive\', …). The instance also attaches a click event to e.g. a link but the event handler does somet

5条回答
  •  借酒劲吻你
    2021-01-27 03:59

    I would keep the same handler and call the appropriate method within.

    var Foo = (function(){
    
        function Foo() {
    
            this.state = 'active';
    
        }
    
        Foo.methodMapping = {
            active: 'a',
            inactive: 'b'
        };
    
        Foo.prototype = {
    
            a: function(){}.
            b: function(){},
    
            handler: function(el) {
    
                // This'll handle the event, I guess
                // (Assuming `this` refers to instance, not element)
    
                var state = this.state;
                if (state in Foo.methodMapping) {
                    return this[Foo.methodMapping[state]].apply(this, arguments);
                } else {
                    // (prob don't need to cover this case)
                }
    
            }
    
        };
    
        return Foo;
    
    }());
    

提交回复
热议问题