Jump to content

Events and/or Callbacks?


clark
 Share

Recommended Posts

I am a Flash dev been toying with TypeScript over the last month.  


One thing that confuses me about JS, is events. window.addEventListener exists but it appears to be part of the dom?  Lets say I have a timer which counts down 5 seconds.  My new class cannot dispatch events, the property does not exist and there is no EventDispatcher?

So in JS/TS games, are events discouraged?  If so, what is the alternative?  Callbacks?

Is a call back just a function I provide? Lets say this just as a basic example?

var timer = new Timer();
timer.onComplete = function(){console.log("test")};
timer.startCountdown(5);


so inside my timer, when countdown is 0, I invoke the onComplete() method?   Is this, in a nutshell, what a callback is?

Finally, what is a closure then??

Thanks guruz :D

Link to comment
Share on other sites

if you want custom DOM event use dispatchEvent()  (https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.dispatchEvent?redirectlocale=en-US&redirectslug=DOM%2FEventTarget.dispatchEvent)

 

if you want to trigger custom behaviour when a condition is verifier then use callbacks ...

 

if you want something more generic here is a TS code I use for my own projects allowing to register, bind and trigger custom events. it also handles multiple events listeners

 

 

	export class EventObj {		_events: any;		constructor() {		}		// Events primitives ======================		bind(event, fct) {			this._events = this._events || {};			this._events[event] = this._events[event] || [];			this._events[event].push(fct);		}		unbind(event, fct) {			this._events = this._events || {};			if (event in this._events === false) return;			this._events[event].splice(this._events[event].indexOf(fct), 1);		}		unbindEvent(event) {			this._events = this._events || {};			this._events[event] = [];		}		unbindAll() {			this._events = this._events || {};			for (var event in this._events) this._events[event] = false;		}		trigger(event, ...args: any[]) {			this._events = this._events || {};			if (event in this._events === false) return;			for (var i = 0; i < this._events[event].length; i++) {				this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1))			}		}		registerEvent(evtname) {			this[evtname] = function (callback, replace) {				if (typeof callback == 'function') {					if (replace) this.unbindEvent(evtname);					this.bind(evtname, callback);				}				return this;			}		}			}

 

you can extend this class to make events available to other classes.

for example to implement your Timer class, this is the code :

 

export class Timer extends EventObj {		constructor() {			super();						this.registerEvent('onComplete')		}				startCountdown(n:number)		{			var _this = this;			setTimeout(function() {				_this.trigger('onComplete');			}, n*1000);		}}

 

 

now you can do :

 

var timer = new Timer();timer.onComplete(function(){console.log("test 1 ")});timer.onComplete(function(){console.log("test 2 ")});// ... other binds timer.startCountdown(5);

 

 

 

 

Edit : Events code is borrowed from https://github.com/jeromeetienne/microevent.js/blob/master/microevent.js#L12-31 I just added unbindAll and unbindEvent and wrapped everything in a TypeScript class

Link to comment
Share on other sites

Hi Chris thanks, I do not feel so much like a looser :P at the moment I am struggling with the larger frameworks like Backbone and the TypeScript layer adds extra confusion. I am going to look into this though, I found a book on amazon I may purchase. 

 

Ezilia, I really appreciate you taking the time to write that and share it, the TS is a real bonus. I found this MicroEvent on the microjs website before I posted here but again the TypeScript layer was causing me issues. It seems familiar to me :D

Thanks lads!

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...