mardi 19 janvier 2016

Design pattern for javascript object literals handling event messages

I'm creating javascript code on a HTML page with several object literals with properties and methods that are basically consumed by main object literal. Each of these objects are only needed once so I used object literals semantics. The main object will primarily be called by events from a Worker object and setInterval/setTimeout timers. Understanding that 'this' is in the scope of the caller (typically window object) I'm looking for an elegant way to manage scoping. For example my current [pseudo] code:

var unit1 = {
    prop1: "data",
    method1: function() {
      // do work with o.prop1
    }
};

// other unitX object literals...

var driverMain = {
    o: null,
    attribute1: "Hello",
    attribute2: "World",
    units: [ unit1, ...],
    evtHandler: function(e) {
        // work with units
        o.attribute1 = "Elegant?";
    }
};
driverMain.o = driverMain;

setTimer(driverMain.evtHandler, 5000);

Is there a more elegant pattern here? Cheers.

Aucun commentaire:

Enregistrer un commentaire