Architecture Flashcards

1
Q

event-based architecture

A

for Timer project we could put all the code into addEventListener for the startTimer Button. For ex., draw part of border on each ticket.

A better alternative approach is to separate responsibilities.
In addEventListener of the startTimer Button we can emit events imforming anyone subscribing to this event that it has occurred.

Emit event that timer has started
Emit event on every tick
Emit event when timer is done

the border of the timer could listen for the event “every tick” and do its own logic separately. In the future, we could any number of other components that would listen to timer events and do something new. For ex., display some text every 5 ticks

In this way, timer events are consolidated in timer component and isolated from all the listeners

in order to emit events, we do the following:

  1. pass an optional object called callbacks into the Timer constructor
  2. the user of the Timer class can decide whether to pass callbacks with his own functionality or just use what is implemented inside Timer
  3. in the Timer constructor we check if the object is passed and if yes - initialize the methods that we expect to be passed inside this object as our class methods

if(callbacks){
this.onStart = callbacks.onStart;
this.onFinish = callbacks.onFinish;
}

  1. Inside our Timer methods where appropriate we use these additional methods, but before - always check if they are avaialble (were passed on with the object callbacks)
const start = () => {
  //some code that is always executed
  if(this.onStart){
    this.onStart();
  }
}
  1. The user who creates our Timer object now can pass his own methods:
var timer = new Timer(param1, param2, {
  onStart(){
    //user's code
  },
  onFinish(){
    //user's code

}
})

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

this and event listeners

A
class Timer{
constructor(button){
  this.button = button;
  this.button.addEventListener(this.someMethod)
}

someMethod(){
console.log(this);
}

someMethodTwo(){

}
}

var timer = new Timer(document.querySelector(‘#myButton’));

////
if we call 

timer.someMethod() —> it will print the Timer object

if we click the button
it will call the method in the class (so in addEventListener(this.someMethod) - THIS refers to the class, which has the method someMethod()), but then inside this method in console.log(this) - THIS will be bound to the button!!!! not to the Timer object!!

so when button is clicked - it will print the button object

if we add another method call inside someMethod() –> it will not even work with the button

someMethod(){
this.someMethodTwo();
}

now if we click the button, we’ll get an Exception

if we try timer.someMethod() - it will work

How well did you know this?
1
Not at all
2
3
4
5
Perfectly