'How can instantiated JavaScript objects communicate with each other?

I think the best way to ask my question is by giving an example.

In JavaScript, imagine the following scenario:

function Tab(options) {
    this.options = options;
}

Tab.prototype.doSomething = function () {
    if(...) {
        // Change tab1's options
        //tab1.disabled = true
    } else {
        // Change tab2's options
        //tab2.disabled = true
    }
    // Call a method on of mySlider instance (NOT myOtherSlider instance)
    //mySlider.helloWorld();
}

// Slider class
function Slider(options) {
   ....
}

Slider.prototype.helloWorld = function () {

    ...
    // Access tab1's properties
    // tab1.disabled should be "TRUE" since it was changed previously

    // Access tab2's properties
    ...
}

function Accordion() {
    this.name = 'accordion';
    var tab1          = new Tab({disabled: true}),
        tab2          = new Tab({disabled: false),
        mySlider      = new Slider({color: red}),
        myOtherSlider = new Slider({color: blue});
}

Pretty much I would like all the classes to be aware of the objects that has been instantiated in their own class as well as other classes.

The important part is for the instances to be synchronized. For example, a change to tab1's properties should be applied/visible to any other objects accessing tab1.


I managed to answer my own question by using an object manager class:

function ObjectManager () {
}

ObjectManager.objects = {};

ObjectManager.register = function (name, object) {
    var t = this;
    t.objects[name] = object;
}

ObjectManager.getObject = function (name) {
    var t = this;
    return t.objects[name];
}

function Tab () {
    this.name = 'tab object';
}

Tab.prototype.init = function (name) {
    var t = this;
    t.name = name;
}

Tab.prototype.changeProperty = function () {
    var tab1 = ObjectManager.getObject('tab1');
    tab1.name = 'changed tab1 name';
}

function Accordion() {
    var tab1 = new Tab();
    tab1.init('tab number 1');

    var tab2 = new Tab();
    tab2.init('tab number 2');

    ObjectManager.register('tab1', tab1);
    ObjectManager.register('tab2', tab2);
    console.log(ObjectManager.objects);
    tab2.changeProperty();
    console.log(ObjectManager.objects);
    console.log(tab1.name);
}

var accordion = new Accordion();​

Though I am not sure how efficient this solution is, but it gets the job done.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source