views:

281

answers:

1

I have a SELECT element which adds its value to a hidden INPUT via Javascript every time an OPTION is clicked (along with a visual representation of each selection) and I'd like to be able to monitor changes for another Javascript function. For the sake of modularity, I can't integrate the second function into the first one. I would also rather not poll the hidden INPUT's value to avoid hacks. Currently I am using the onclick event on the DIV that contains both the SELECT and the hidden INPUT, but that's also quite hack-ish. Do you know a way to monitor a hidden INPUT element for changes?

+3  A: 

So, you have:

  • Function A, which updates the hidden INPUT.
  • Function B, which should be called when the INPUT is updated.

Why not create an "event" of your own that that function A calls/dispatches whenever it is done working?

I believe most Javascript frameworks support the concept of custom events pretty easily, but it's just a series of function calls.

For example, create some object D which represents the dispatcher for a single event. Yes this is silly, but I'm trying to keep the concept simple. This object D, holds a list of functions which have "registered" for its event, and when the event is dispatched, it calls those functions.

Something like:

var d = (function() {
    var funcs = [];

    function fire() {
        for (var i=0; i<funcs.length; ++i) {
          funcs[i].call();
        }
    }

    function register(newfunc) {
        funcs.push(newfunc);
    }    

    return {
        fire: fire,
        register: register
    };
})();

You just have two things left to do - make function A fire the event:

function A() {

    // do stuff to update the INPUT

    d.fire();
}

and also, onload, "register" function B to be called when the event happens:

d.register(B);

This approach maintains the seperation-of-modules principle (or whatever its called) since A and B know nothing of each other, and only need to know about a third object.

scraimer