Friday, April 27, 2018

How To Load HTML5 Video After Video Ends and Set Controls List Attribute In React?

In modern browsers, adding a video to your page is as easy as adding an image. I am not going on detail on how HTML5 Video works.

It is very easy to add HTML5 video in React. React DOM now supports these media events on audio and video tags: onAbort, onCanPlay, onCanPlayThrough, onDurationChange, onEmptied, onEncrypted, onEnded, onError, onLoadedData, onLoadedMetadata, onLoadStart, onPause, onPlay, onPlaying, onProgress, onRateChange, onSeeked, onSeeking, onStalled, onSuspend, onTimeUpdate, onVolumeChange, onWaiting.

In this tutorial, you can see how to add HTML5 video tag controlsList attribute in React and how to load the video to the beginning of the video or start frame again after video has ended.

componentDidMount() {
  .forEach( x => x.setAttribute("controlsList","nodownload noremoteplayback"));

onVideoEnded = (index) => {
   var video = document.querySelector('#video'+index);

return (
  <video id="video1" controls muted src="" 
  onEnded={() => this.onVideoEnded('1') />

These are only some of used properties, event and method of HTML5 Video in this article. For more details, please visit HTML5 Video.

controls => Shows the default video controls (play, pause, etc).
muted => Mutes the audio from the video
Used Event
onEnded => Fired when the video has finished playing
Used Method
load() => method loads the video and reset the play head to the beginning of the video

Wednesday, January 31, 2018

How To Update To The Latest Node.js Version On a Mac?

N is an npm-based node version manager. You can install it by installing first some version of node and then running
 npm install -g n
Assuming you have successfully installed n. The following will install the latest version of node.
 sudo n latest
Latest version by the time the article was published: v9.4.0

You can use Nvm or Homebrew as well.

Thursday, December 7, 2017

Map, Filter and Reduce In Javascript

map creates a new array by transforming every element in an array, individually.
filter creates a new array by removing elements that don't belong.
reduce, on the other hand, takes all of the elements in an array, and reduces them into a single value.

Suppose we have an app that maintains an array of your tasks for the day. Each task is an object, each with a name and duration property:
// Durations are in minutes
var tasks = [ 
    'name'     : 'Write for Envato Tuts+', 
    'duration' : 120 
    'name'     : 'Work out', 
    'duration' : 60 
    'name'     : 'Procrastinate on Duolingo', 
    'duration' : 240 

map in Practice

Let's say we want to create a new array with just the name of each task, so we can take a look at everything we've gotten done today.

Using map, we can write:
var task_names = (task, index, array) { 

// Using ES6 arrow functions
 var task_names = => );

filter in Practice

The next of our array operations is filter. It takes an array, and filters out unwanted elements. Let's revisit our task example. Instead of pulling out the names of each task, let's say I want to get a list of just the tasks that took me two hours or more to get done.

Using filter, we can write:
var difficult_tasks = tasks.filter(function (task) {
    return task.duration >= 120;
// Using ES6 arrow functions
var difficult_tasks = tasks.filter((task) => task.duration >= 120 );

reduce in Practice

Let's turn back to our tasks example. What If we wanted to know the total amount of time we spent working today?

With reduce, that becomes:
var total_time = tasks.reduce(function (previous, current) {
    return previous + current.duration;
}, 0);
// Using ES6 arrow functions
var total_time = tasks.reduce((previous, current) previous + current.duration );

In this tutorial, you've learned how map, filter, and reduce work; how to use them; and roughly how they're implemented.

For detailed explanation, visit How to Use Map, Filter, & Reduce in JavaScript

Thursday, November 23, 2017

Understanding Three Cases of Components Communication in Vue 2.0

The way components communicate, in Vue 2.0, is through props and custom events. And with Vue 2.0 release, it has actually gotten simpler. So, in this article, I’d like to show you the different cases in which components communicate, and how to handle each one properly.

Three cases of components communication:
1. From parent to direct children, no custom events required; just use props.
2. From a child to its direct parent, use $emit(eventName) in children and the directive v-on:event-name in the parent.
3. Non Parent-Child communication i.e global component communication (from any component to any component), use the global event bus. Or use Vuex for more complex cases.

1. Parent-Child communication

It's called parent-child communication because they are directly related to each other. They inevitably need to communicate to one another: the parent may need to pass data down to the child, and the child may need to inform the parent of something that happened in the child.

In Vue, the parent-child component relationship can be summarized as props down, events up. The parent passes data down to the child via props, and the child sends messages to the parent via events.

Pssing data with props
Data can be passed down to child components using props. A prop is a custom attribute for passing information from parent components. A child component needs to explicitly declare the props it expects to receive using the props option:
  <div class="message">
    {{ message }}

 export default {
   name: "child",
   props: ['message'] 
Then we can pass a plain string to child component from parent like so:
 <child message="hello!"></child>

2. Child-Parent Communication

We have learned that the parent can pass data down to the child using props, but how do we communicate back to the parent when something happens? This is where Vue's custom event system comes in.

To accomplish this kind of communication, you have to do two things:
1. First, Fire an event from the child component using $emit(eventName, [data]).
2. Listen to it on the parent using the v-on:event-name directly in the template where the child component is used.

Here’s a quick example:
Let’s say you’ve built your own custom dropdown component that contains a bunch of options which you pass from the parent. When an option is selected in that dropdown, it should emit an event to its parent, so it can do its stuff.

Here’s what happens when an option is selected in Dropdown.vue:
data () {
 return {
   selectedOption: null
methods: {
  selected () {
    // assume 'this.selectedOption' is defined in the data object
    this.$emit('option-select', this.selectedOption)
Now in the parent component — let’s call it NavBar.vue — we’ll have something like this (note that I’m using the shorthand for v-on which is @):
  <div class="nav-bar">
    <!-- other elements -->

  export default {
    methods: {
      onOptionSelect (option) {
      // handle it here

3. Non Parent-Child communication

Sometimes two components may need to communicate with one-another but they are not parent/child to each other. In other words, global component communication.

You need to handle all the communications through event hub (or some call it event bus). In its simplest definition, it's an empty Vue instance that you use globally to fire and listen for events anywhere you want in the component's tree.

As I just mentioned, this eventHub is an empty Vue instance which you’d create like this:
 //empty Vue instance 
 var eventHub = new Vue()
This needs to be globally accessible
For everything to work correctly, you need to make sure that this eventHub is accessible globally. And this depends on how your application is structured.

If you’re building a simple non-modular app, you can attach that instance to the browser’s window object.

However, for module-based applications that use bundling tools like Webpack or Browserify, you can do that by exporting that instance from a certain file and then import it wherever you need it.
 // src/shared/EventHub.js

 import Vue from 'vue'
 export default new Vue()
Now in other components, you would import it like this:
 import eventHub from 'src/shared/EventHub'
Let’s imagine that we want to pass an event from component-A to component-B. To do that, we first need to emit that event from component-A:
 import eventHub from 'src/shared/EventHub'

// …

methods: {
  doSomething () {
    eventHub.$emit('id-selected', 1)
Now, in component-B, you would listen to it like this:
 import eventHub from 'src/shared/EventHub'

 // …

 mounted () {
 // in component B's created hook  
 eventHub.$on('id-selected', (id) => {
     // handle it however you want.

As simple as that! The great thing about this approach is that you're no longer concerned about the components tree structure. In other words, events can be emitted from any component and handled by any other component regardless of their relationship.

In more complex cases, you should consider to use Vuex.

Understanding Components Communication in Vue 2.0
Vue.js Components

Wednesday, October 25, 2017

How To Add Custom Helpers on Handlebars?

You can extend handlebars with your own custom helpers. This allows you to create complex logic using handlebar’s expression system. There are 2 kinds of helpers, a function helper and a block helper. The difference is that one is meant for a single expression and the other uses a block expression.

Custom Function Helpers
Creating function helpers is relatively easy. To create one, we have to register it using the registerHelper() method. It takes the name of the helper and the helper function as arguments. Handlebars.js takes whatever is returned from the helper function and writes it out to the template, so be sure to always return a string from your custom helpers.

To write an expression helper function to output a formatted phone number, you could define the following helper:
Handlebars.registerHelper("formatPhoneNumber", function(phoneNumber) {
  phoneNumber = phoneNumber.toString();
  return "(" + phoneNumber.substr(0,3) + ") " + phoneNumber.substr(3,3) + "-" + phoneNumber.substr(6,4);
You would use the formatPhoneNumber helper in a template like this:
{{formatPhoneNumber phoneNumber}}

Custom Block Helpers
Custom block helpers are also registered with the Handlebars.registerHelper method. When a helper is used with a block, Handlebars will pass the contents of the block compiled into a function to the helper.

Here's an example block helper that compare the option with a value, letting the contents know whether a value is equal to option. If the option is an equal to a value, helper just returns the 'selected' attribute else return empty string. This helper is useful to add a 'selected' attribute conditionally on any of the option elements.
Handlebars.registerHelper("selected", function(option, value) {
 if (option === value) {
        return 'selected';
    } else {
        return '';

You would use the selected helper in a template like this:
<select name="countries" >
 <option  value="{{code}}" {{selected code "46" }>{{country_name}}({{code}})</option>
If the country code is equal to 46 i.e Sweden, the option will be selected.

Ref: Custom Helpers – Handlebars.js Tutorial