6/6/19

When You Should Use Subject

Subject - Who are you?

Yes, lot of us (angular people) have heard about subjects. Yes, it is something that acts like observable (you can subscribe to it):


const subject = new Subject();
...
subject.subscribe(x => console.log(x));

And simultaneously you also can call "next" method, like in observer:

 ...
 const button = document.querySelector('button')
 button.addEventListener("click", () => subject.next('click')); 
 ...

Ok, great, but... when it is good practice to use this Subject thing? you may ask...

Lets look on what Angular guys are Doing

Everybody who starts with "get started" section of angular - knows about "heroes tour" tutorial.
Quick search shows the use of "Subject" in the HeroSearchComponent.
Here you have a pretty common scenario: a search input which have to trigger a search request and populate with response results a list below the input...
So in "input" event handler you expect to see something like this:


  search(term: string): void {
    this.heroService.searchHeroes(term).subscribe(results => this.heroes = results);
  }

Or, when displaying the data using "Async" pipe, something like:

/*    
   <li *ngFor="let hero of heroes$ | async" >
      <a routerLink="/detail/{{hero.id}}">
        {{hero.name}}
      </a>
    </li>
*/
  search(term: string): void {
    this.heroes$ = this.heroService.searchHeroes(term);
  }

The problem with this code (although it will work) - is that the subscription to "searchHeroes" method is done each time when search terms changes, (not mention is already done at "ngOnInit" lifehook of the component):

 ngOnInit(): void {
    this.heroes$ = this.searchTerms.pipe( // pipe is the equivalent of "subscribe"
      // wait 300ms after each keystroke before considering the term
      debounceTime(300),

      // ignore new term if same as previous term
      distinctUntilChanged(),

      // switch to new search observable each time the term changes
      switchMap((term: string) => this.heroService.searchHeroes(term)),
    );
  }

And it is bad to subscribe multiple times, because of memory leaks potential. Instead - by using searchTerms Subject(like Angular guys did), you can call the "next" and trigger the service again, which is much more accurate:

  // Push a search term into the observable stream.
  search(term: string): void {
    this.searchTerms.next(term);
  }
 

5/2/19

How To Attach 'AddEvenlistener' Correctly

One of my recent tasks was - to implement the site side menu list (using vanilla javascript), and I was very glad to take a challenge - and practice my vanilla skills. I like to use vanilla - since I think it will replace in short future all the frameworks like react & angular...
Yes it sad (because I big fun of frameworks) but lets face the truth - javascript (or ECMASCRIPT) is developing very fast and already doing most of things we needed frameworks for...

Lets Focus, The Menu

So, menu is the very simple one, with links to all site subpages, but the goal is - that clicks on items should be handled only by javascript


<ul class="menu">
  <li><a href="javascript: void(0)">1 menu</a></li>
  <li><a href="javascript: void(0)">2 menu</a></li>
  <li><a href="javascript: void(0)">3 menu</a></li>
</ul>

For simplicity sake - lets say that "handle" means - to print the textContent of clicked item to the console.

First Try

So my first solution was to capture all the 'a' elements using "querySelectorAll" native method, and attach listeners to each of the using "forEach" loop:


document.querySelectorAll('ul.menu a')
.forEach(menuItem => menuItem.addEventListener('click', ({target}) => {
  console.log(target.textContent); // printing '1 menu' when first menu clicked 
}))

Second Look

After giving the code a second look - I suddenly figured out the things may be done much more simply - by attaching the listener only to parent 'ul' element:


document.querySelector('ul.menu').addEventListener('click', ({target}) => {
  console.log(target.textContent)
})

The advantage (except from simplicity) of this attitude is that instead of many listeners we using only one (which is much more performant)

Conclusion

The main reason we can use only one listener for many elements is the advantage of using "target" - the way to identify the element user clicked inside the parent element. The important thing here - is to know that event argument has also "currentTarget" property, and unlike "target"(which set to element the user actually clicked upon) - the "currentTarget" set to element the listener attached to

4/14/19

For the first time in my life - i dare to interview the interviewer

Recently I went to some job interview, which i, lets face the truth - totally failed. Since my career as developer last longer than 10 years, and had chance to work in a lot of places and on a lot of projects - it is definitely not my first interview, and event not first failed interview. Yet, at this post I want to tell you about some unique experiences I had during this particular adventure.

Details

Lets start from the beginning: It was an interview for the front-end position, and i was asked some javascript questions, like: how to check if a variable is an Array, or: how to prevent click event from bubbling from a child element to its parent. To be honest - I found myself caught unprepared for those questions (since almost year im working as a devops and completely forgot the differences between currentTarget and target, e.preventDefault and e.stopPropagation - shame on me!).
Yet the interesting thing was, that at some point, instead of focusing on my loose situation - I found myself trying to analyze the situation of the team that seeking to hire some frontend developer - and how it would be feel like working at this team

Conclusions

Here are some conclusions I come up with:

  • The interviewer didnt knew about ES Array.isArray method (instead - the answer he considered right was
    
    variableToCheck.constructor === Array
    
    
    )
  • Interviewer was surprised to find about existence of native javascript "fetch" method - instead he preferred to use jQuery ajax method for doing ajax request
  • The question about stopPropagation was a part of question:
    "how do you prevent a click on some element inside modal window to propagate to an overlay, when implementing modal dialog"
    - i tried to point out that nowadays browsers come up with a dialog HTML5 element which do exactly the dialog scenario (without need of coding anything) - but again caught the interviewer by surprise

Summary

Things can have various - a negative and a positive angles. At least I finally find out that as much important as to prepare yourself well for an interview - It is also important to try and figure out: what kind of work need to be done in the place you apply for. For example - this place did the impression of building some kind of new javascript framework instead of using some current, much better and simplier existing tools - a work I for sure would not be comfortable doing...

When You Should Use Subject

Subject - Who are you? Yes, lot of us (angular people) have heard about subjects . Yes, it is something that acts like observable (you can ...