0

I have two objects. ObjecA triggers an event E and ObjectB has to listen for the event which was triggered by ObjectA (E). ObjectA sends only when a property in it changes at run time.

Thanks in advance.

1
  • 1
    There are lots of different ways. But what they'll have in common is that an object that can be observed will have a list (possibly an array) of handlers for its events (probably organized by event) and when the conditions are right for the event, it will call those functions. It would also have a means of adding to an event's list of handlers, and removing from it. Etc. Have a go and if you have a specific question about a problem you have during implementation, post that. See also Observer pattern. Commented Aug 29, 2016 at 11:00

2 Answers 2

1

You can use pubsub pattern

var pubsub = {};

(function(myObject) {

  // Storage for topics that can be broadcast
  // or listened to
  var topics = {};

  // An topic identifier
  var subUid = -1;

  // Publish or broadcast events of interest
  // with a specific topic name and arguments
  // such as the data to pass along
  myObject.publish = function(topic, args) {

    if (!topics[topic]) {
      return false;
    }

    var subscribers = topics[topic],
      len = subscribers ? subscribers.length : 0;

    while (len--) {
      subscribers[len].func(topic, args);
    }

    return this;
  };

  // Subscribe to events of interest
  // with a specific topic name and a
  // callback function, to be executed
  // when the topic/event is observed
  myObject.subscribe = function(topic, func) {

    if (!topics[topic]) {
      topics[topic] = [];
    }

    var token = (++subUid).toString();
    topics[topic].push({
      token: token,
      func: func
    });
    return token;
  };

  // Unsubscribe from a specific
  // topic, based on a tokenized reference
  // to the subscription
  myObject.unsubscribe = function(token) {
    for (var m in topics) {
      if (topics[m]) {
        for (var i = 0, j = topics[m].length; i < j; i++) {
          if (topics[m][i].token === token) {
            topics[m].splice(i, 1);
            return token;
          }
        }
      }
    }
    return this;
  };
}(pubsub));



Implementation:
  // Another simple message handler

  // A simple message logger that logs any topics and data received through our
  // subscriber
  var messageLogger = function(topics, data) {
    console.log("Logging: " + topics + ": " + data);
  };

// Subscribers listen for topics they have subscribed to and
// invoke a callback function (e.g messageLogger) once a new
// notification is broadcast on that topic
var subscription = pubsub.subscribe("inbox/newMessage", messageLogger);

// Publishers are in charge of publishing topics or notifications of
// interest to the application. e.g:

pubsub.publish("inbox/newMessage", "hello world!");

// or
pubsub.publish("inbox/newMessage", ["test", "a", "b", "c"]);

// or
pubsub.publish("inbox/newMessage", {
  sender: "[email protected]",
  body: "Hey again!"
});

// We can also unsubscribe if we no longer wish for our subscribers
// to be notified
pubsub.unsubscribe(subscription);

// Once unsubscribed, this for example won't result in our
// messageLogger being executed as the subscriber is`enter code here`
// no longer listening
pubsub.publish("inbox/newMessage", "Hello! are you still there?");

Sign up to request clarification or add additional context in comments.

Comments

0

you can use watch

var a = {"x":5}
a.watch("a", function( prop, oldval, newval ) {
// your event code here
}

watch not work in chrome browser you can use this code

if ( !Object.prototype.watch ) {
    Object.defineProperty( Object.prototype, "watch", {
        enumerable: false,
        configurable: true,
        writable: false,
        value: function( prop, handler ) {
            var oldval = this[ prop ],
                newval = oldval,
                getter = function() {
                    return newval;
                },
                setter = function( val ) {
                    newval = val;
                    return handler.call( this, prop, oldval, newval );
                };

            if ( delete this[ prop ] ) { // can't watch constants
                Object.defineProperty( this, prop, {
                    get: getter,
                    set: setter,
                    enumerable: true,
                    configurable: true
                });
            }
        }
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.