如何使用JavaScript扩展onchange事件

Bri*_*ian 6 html javascript onchange

这是我在扩展元素的JavaScript onchange事件时遇到的一个问题.我有几个select元素有条件地将每个onchange事件附加到每个元素上(当它们更改为特定值时,它会隐藏/取消隐藏某些元素).我想有条件地添加或附加到另一个onchange事件,以便他们设置一个全局变量,如果他们确实更改而不修改或禁用已附加到它们的上一个函数.有没有办法"附加"附加功能或在现有功能上添加更多功能?

以下是我认为的例子:

<select id="selectbox1">
    <option>...</option>
    <option>...</option>
</select>

if (<certain conditions>) {
    document.getElementById("selectbox1").onchange = function () { 
        //hides elements to reduce clutter on a web form ...
    }
}
....
if (<other conditions>) {
    document.getElementById("selectbox1").onchange = function2 () {
        //set global variable to false
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,我想简单地将1-liner"set global variable to false"添加到原始函数中.

Joe*_*nez 9

你可以通过简单地使用一个调用其他函数的复合函数来作弊.

document.getElementById("selectbox1").onchange = function() {
    function1();
    function2();
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用Pro JavaScript Design Patterns一书中描述的观察者模式.我在一篇文章(这里)中有一个例子.

//– publisher class — 
function Publisher() { 
    this.subscribers = []; 
};

Publisher.prototype.deliver = function(data) { 
    this.subscribers.forEach(function(fn) { fn(data); }); 
};

//– subscribe method to all existing objects 
Function.prototype.subscribe = function(publisher) { 
    var that = this; 
    var alreadyExists = publisher.subscribers.some(function(el) { 
        if (el === that) { 
            return; 
        } 
    });

    if (!alreadyExists) { 
        publisher.subscribers.push(this); 
    } 
    return this; 
};
Run Code Online (Sandbox Code Playgroud)