There are at least two ways to achieve this:
- If you are a jQuery user (currently I am not), you can wrap your simple JavaScript object using jQuery and then, as DOM elements, it will be able to listen to events. This method already has an answer here . I'm not sure how this method works under the hood, I plan to study it later, and you can explore it yourself.
- Using VanillaJS, you can achieve the same effect by creating an eventful class from which all objects that want to interact will be created and created. Then all instances of this class will be able to register, emit and broadcast the event. Borrowing the semantics from the DOM API and AngularJS, I wrote an example demonstrating how this can be done and how it can be used. There he is:
var EventfulObject = function() { var event = {}; var instances = []; var EventfulObjectConstructor = function() { instances.push(this); }; EventfulObjectConstructor.prototype = { broadcast: function(name) { instances.forEach(function(instance) { (instance.hasOwnProperty("receiveBroadcast") && typeof instance["receiveBroadcast"] === "function") && instance["receiveBroadcast"](name); }); }, emit: function(name) { event.hasOwnProperty(name) && event[name].forEach(function(subscription) { subscription.process.call(subscription.context); }); }, on: function(name, action) { event.hasOwnProperty(name) || (event[name] = []); event[name].push({ context: this, process: action }); var subscriptionIndex = event[name].length - 1; return function() { event[name].splice(subscriptionIndex, 1); }; } }; return EventfulObjectConstructor; }(); var Model = function(id) { EventfulObject.call(this); this.id = id; this.receiveBroadcast = function(name) { console.log("I smell another " + name + "; and I'm model " + this.id); }; }; Model.prototype = Object.create(EventfulObject.prototype); Model.prototype.constructor = Model;
<h1>THE CODE IS IN the JavaScript pane!</h1> <h3>AND... THE SHOW IS ON YOUR CONSOLE!</h3>
You can use this as a basis for a more reliable solution.
source share