{"id":62,"date":"2015-12-03T07:51:28","date_gmt":"2015-12-03T02:21:28","guid":{"rendered":"http:\/\/madhurendra.com\/?p=62"},"modified":"2015-12-03T07:54:51","modified_gmt":"2015-12-03T02:24:51","slug":"javascript-domless-events","status":"publish","type":"post","link":"https:\/\/madhurendra.com\/javascript-domless-events\/","title":{"rendered":"Javascript Domless events"},"content":{"rendered":"
Using jQuery or nodejs makes you addicted to pubsub (publish\/subscribe) model.
\nNodejs has nattive support for event emitters but javascript doesn’t have. Events are only binded to a DOM, using which doesn’t make sense and its also adds to performance cost.<\/p>\n
To solve the problem i wrote a custom class which implements `on` and `emit` method, Yes some methods like `once` are missing.<\/p>\n
var tikEvent = function () {\r\n this.listeners = {};\r\n\r\n};\r\ntikEvent.prototype.on = function (event, callback) {\r\n if (!this.listeners.hasOwnProperty(event)) {\r\n this.listeners[event] = [];\r\n }\r\n this.listeners[event].push(callback);\r\n};\r\n\r\ntikEvent.prototype.emit = function (event) {\r\n if (this.listeners.hasOwnProperty(event)) {\r\n var args = Array.prototype.slice.call(arguments);\r\n args.shift();\r\n\r\n for (var i = 0; i < this.listeners[event].length; ++i) {\r\n try {\r\n this.listeners[event][i].apply(null, args);\r\n } catch (e) {\r\n console.error(e);\r\n }\r\n }\r\n }\r\n};\r\n\r\n\r\n\/\/Some test code.\r\n\r\nvat test = new tikEvent();\r\ntest.on('emitted',function(d){\r\n\r\nconsole.log(d);\r\n}\r\n\r\ntest.emit('emitted',\"test\");<\/pre>\n","protected":false},"excerpt":{"rendered":"Using jQuery or nodejs makes you addicted to pubsub (publish\/subscribe) model. Nodejs has nattive support for event emitters but javascript doesn’t have. Events are only binded to a DOM, using which doesn’t make sense and its also adds to performance cost. To solve the problem i wrote a custom class which implements `on` and `emit` … <\/p>\n