About Me

My photo
PLANO, Texas, United States

Wednesday, October 14, 2020

Javascript used in LWC

In this article, I will be talking about javascript used in LWC.

Function in Javascript

A JavaScript function is a block of code designed to perform a particular task.


// Traditional Function syntax

function name(parameter1, parameter2) {

  // code to be executed

}


// Traditional Function

function (a,b){

   return a + b;

}


//Arrow function 

(parameter1, parameter2) => {

  // code to be executed

}

//Arrow function

(a,b)=>{

   return a+b;

}


“this” in traditional function vs Arrow function


Traditional functions default this to the window scope:


// Traditional Function

window.age = 10; // <-- notice me?

function Person() {

 this.age = 42; // <-- notice me?

 setTimeout(function () { // <-- Traditional function is executing on the window scope

   console.log("this.age", this.age); // yields "10" because the function executes on the window scope

 }, 100);

}

var p = new Person();

The output > "this.age" 10


Arrow functions do not default this to the window scope rather they execute in the scope they are created:


// Arrow Function

window.age = 10; // <-- notice me?

function Person() {

 this.age = 42; // <-- notice me?

 setTimeout(() => { // <-- Arrow function executing in the "p" (an instance of Person) scope

   console.log("this.age", this.age); // yields "42" because the function executes on the Person scope

 }, 100);

}

 

var p = new Person();

The output> "this.age":42


What are the events?

Events are actions that happen when a user interacts with the page - like clicking an element, typing in a field, or loading a page.


The browser notifies the system that something has happened and that it needs to be handled. It gets handled by registering a function, called an event handler, that listens for a particular type of event.

Types of Event

Typically, events are generated by user actions such as mouse clicks and key presses. In addition, events can be generated from code. For example, if you want to notify to the user of any action performed using ShowToastEvent.


To generate an event programmatically, you follow these steps:

  • First, create a new Event object using the Event constructor.

  • Then, trigger the event using element.dispatchEvent() method.

const event = new Event('build');

// Listen for the event.

elem.addEventListener('build', function (e) { /* ... */ }, false);

// Dispatch the event.

elem.dispatchEvent(event);

Handling Events in JavaScript

When an event occurs, you can create an event handler which is a piece of code that will execute to respond to that event. An event handler is also known as an event listener. It listens to the event and responds accordingly to the event fires.


An event listener is a function with an explicit name if it is reusable or an anonymous function in case it is used one time.


An event can be handled by one or multiple event handlers. If an event has multiple event handlers, all the event handlers will be executed when the event is fired.


<script>

    function showAlert() {

        alert('Clicked!');

    }

</script>

<input type="button" value="Save" onclick="showAlert()">

Construct JSON or add a new Node

JSON data is written as name/value pairs, just like JavaScript object properties.

A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:

"firstName":"John"

JSON Objects

JSON objects are written inside curly braces. Just like in JavaScript, objects can contain multiple name/value pairs:

{

"firstName":"John", 

"lastName":"Doe"

}

Json node can be added in two ways:

object["property"] = value;

or

object.property = value;



//Define empty Json

const jsonbody = {};

//Add nodes

jsonbody['Name']='Manoj';

jsonbody['age']=23;

jsonbody.gender = 'Female';

console.log(jsonbody);

Result-> { Name: "Manoj", age: 23, gender: "Female" }



JSON.stringify()

The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

What is a callback?

  • In JavaScript, a callback is a function passed into another function as an argument to be executed later.

  • Callbacks are a way to make sure a certain code doesn’t execute until another code has already finished execution.

  • A callback is important here because we need to wait for a response from the server before we can move forward in our code. We don’t know if our API request is going to be successful or not so after sending our parameters to search/tweets via a get request, we wait. Once Twitter responds, our callback function is invoked. 


Promise

Imagine that you’re a top singer, and fans ask day and night for your upcoming single.

To get some relief, you promise to send it to them when it’s published. You give your fans a list. They can fill in their email addresses so that when the song becomes available, all subscribed parties instantly receive it. And even if something goes very wrong, say, a fire in the studio, so that you can’t publish the song, they will still be notified.

Everyone is happy: you because the people don’t crowd you anymore, and fans, because they won’t miss the single.

This is a real-life analogy for things we often have in programming:

  1. A “producing code” that does something and takes time. For instance, some code that loads the data over a network. That’s a “singer”.

  2. A “consuming code” that wants the result of the “producing code” once it’s ready. Many functions may need that result. These are the “fans”.

  3. A promise is a special JavaScript object that links the “producing code” and the “consuming code” together. In terms of our analogy: this is the “subscription list”. The “producing code” takes whatever time it needs to produce the promised result, and the “promise” makes that result available to all of the subscribed code when it’s ready.


let p= new Promise((resolve,reject)=>{

   let a=1+3;

   if(a===2){

       resolve('success');

   }else{

       reject('failed');

   }

})

 

p.then((msg)=>{

   console.log('This is in then '+msg);

}).catch((error)=>{

   console.log('This is in catch '+error);

})


No comments:

Post a Comment