Friday, February 23, 2024
 Popular · Latest · Hot · Upcoming
121
rated 0 times [  125] [ 4]  / answers: 1 / hits: 15581  / 15 Years ago, wed, june 3, 2009, 12:00:00

This is a question I ran into about expanding on an element's JavaScript onchange event. I have several select elements that conditionally will have one onchange event attached to each of them (when they change to specific values, it hides/unhides certain elements). I want to conditionally add or append to another onchange event so they set a global variable if they do change without modifying or disabling the previous function already attached to them. Is there a way to append an additional function or add more functionality onto the already existing one?



Here is what I believe an example would be like:



<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
}
}


Alternatively I'd like to simply add the 1-liner set global variable to false to the original function.


More From » html

 Answers
22

You can cheat by simply having a composite function that calls the other functions.



document.getElementById(selectbox1).onchange = function() {
function1();
function2();
}


You can also use the observer pattern, described in the book Pro JavaScript Design Patterns. I have an example of its use in an article (here).



//– 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;
};

[#99395] Saturday, May 30, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kevenirvina

Total Points: 315
Total Questions: 112
Total Answers: 84

Location: Vanuatu
Member since Fri, May 13, 2022
2 Years ago
kevenirvina questions
Tue, Jul 28, 20, 00:00, 4 Years ago
Mon, Jul 6, 20, 00:00, 4 Years ago
Wed, Mar 25, 20, 00:00, 4 Years ago
Thu, Jan 2, 20, 00:00, 4 Years ago
;