0

So I'm basically just trying to add watchers to Javascript's Getter/Setter functions but having no luck yet.

KnockoutJS (http://knockoutjs.com) does this with .track().

A YouTube video example of track() in use:
https://www.youtube.com/watch?v=MNiUcuo3Wio

This leads me to my first question, does __defineGetter__ and __defineSetter__ only apply to objects and not string literals?

Here's a code example of how this would ideally work, it may clarify some things.

// Knockout-like tracker in NodeJS.

function track(trackObj, callback) {

  if (!trackObj) return;

  trackObj.__defineCallback__ = callback;

  trackObj.__defineGetter__('value', function() {
    return 'something';
  });

  trackObj.__defineSetter__('value', function() {
    console.log("fn called");
    if (trackObj.__defineCallback__)
      trackObj.__defineCallback__("new value");
  });

}

var something = "track me!";

track(something, function(newValue) {
  console.log("Something has changed to: " + newValue);
});

something = "I have changed."; // Trigger the update callback function.
Levi Roberts
  • 1,277
  • 3
  • 22
  • 44

1 Answers1

0

I've created a simple solution although I'm not quite happy with it. For that reason, I'll leave this question as unanswered for now.

One of the disadvantages is that you can only track a single property with the same name. To get around this, you could put the following code in NodeJS module and create a new tracker object for each item you'd like to track. This would work with same named variables too. Handling all of the different tracker objects could get confusing though.

var tracker = {};
var trackerValues = {};

function track(trackName, callback) {

  Object.defineProperty(tracker, trackName, {

    set: function(toValue) {
      trackerValues[trackName] = toValue;
      if (callback) callback();
    },

    get: function() {
      return trackerValues[trackName];
    }

  });
}

tracker.something = "track me!";

track("something", function() {
  console.log("Something has changed to: " + tracker.something);
});

track("somethingElse", function() {
  console.log("SomethingElse has changed to: " + tracker.somethingElse);
});

tracker.something = "I have changed.";
tracker.something = "I have changed again!";
tracker.somethingElse = "We can track multiple objects";


And a JSBin example of this working:
http://jsbin.com/bunonaca/1/edit?js,console

Levi Roberts
  • 1,277
  • 3
  • 22
  • 44