Saturday, March 9, 2019

Javascript: Array Helper Methods

forEach()

forEach() is usually used as a replacement for traditional for-loop. Lets add an array of numbers. In classic Javascript, this is how you will write the code:
var numbers = [11, 12, 13, 14, 15];

var sum = 0;

for (var i = 0; i < numbers.length; i++) {
  sum += numbers[i];
}

console.log(sum);

Using forEach helper method, the code will be something like below:
var numbers = [11, 12, 13, 14, 15];

var sum = 0;

numbers.forEach(function(number) {
  sum += number;
});

console.log(sum);

The iterator function doesn't have to be an anonymous function. We can declare a function separately and then pass it in forEach as below:
var numbers = [11, 12, 13, 14, 15];

var sum = 0;

function addNumbers(number) {
  sum += number;
}

numbers.forEach(addNumbers);

console.log(sum);

map()

Write a loop that iterates over a list of numbers, doubles the value of each number in the array and then pushes the doubled number into a new array.

In classic JS, this is how the code will look like:
var numbers = [11, 12, 13, 14, 15];

var double = [];

for (var i = 0; i < numbers.length; i++) {
  double.push(numbers[i] * 2);
}

console.log(double);

Now we will refactor the code above to use the map helper.
var numbers = [11, 12, 13, 14, 15];

var double = numbers.map(function(number) {
  return number * 2;
});

console.log(double);

You can also reformat the code like below:
var numbers = [11, 12, 13, 14, 15];

var doubleFn = (num) => num * 2;

var double = numbers.map(doubleFn);

console.log(double);

One of the most common uses of map is collecting properties of an array of object. Check the code below:
const persons = [
  {firstName:"John", lastName:"Doe"},
  {firstName:"Mike", lastName:"Crusoe"},
];

const firstNames = persons.map(person => person.firstName);

console.log(firstNames);

filter()

We will be filtering out persons who are working in Finance department. This is how we will write code in classic Javascript:
var persons = [
  {firstName:"John", lastName:"Doe", age:46, department:"Finance"},
  {firstName:"Mike", lastName:"Crusoe", age:40, department:"Finance"},
  {firstName:"Mary", lastName:"Jane", age:30, department:"HR"}
];

var filteredPersons = [];

for (var i = 0; i < persons.length; i++) {
  if (persons[i].department === "Finance") {
    filtered.push(persons[i]);
  }
}
console.log(filteredPersons);

Now we will refactor the code above to use the filter helper.
const persons = [
    { firstName: "John", lastName: "Doe", age: 46, department: "Finance" },
    { firstName: "Mike", lastName: "Crusoe", age: 40, department: "Finance" },
    { firstName: "Mary", lastName: "Jane", age: 30, department: "HR" }
];

const filteredPersons = persons.filter(person => person.department === 'Finance');

console.log(filteredPersons);

find()

This method will return only first element where callback function returns true; it don't process other elements.

We will search for user whose name is Mike. This is how we will write code in classic Javascript:
var users = [
  {name:"John"},
  {name:"Mike"},
  {name:"Mary"}
];

var user;

for (var i = 0; i < users.length; i++) {
  if (users[i].name === 'Mike') {
    user = users[i];
    break;
  }
}

console.log(user);

Now we will refactor the code above to use the find helper.
const users = [
  {name:"John"},
  {name:"Mike"},
  {name:"Mary"}
];

const user = users.find(user => user.name === 'Mike');

console.log(user);

Share This:    Facebook Twitter

Friday, March 8, 2019

Javascript: Arrow functions and this

Arrow functions are anonymous; there are only arrow function expressions. You can assign arrow function expression to a variable, can be used in an IIFE as well as a callback function. Below you will find valid arrow functions:

(a, b) => a + b // implicitly returning a + b

(a, b) => {                // explicitly returning a + b
   return a + b;
}

a => a * a                // omit () when there is one parameter

() => 2                   // () mandatory when there are no parameters

(a, b) => {               // explicitly returning JS object
   return {
      a1: a, b1: b
   }
}

(a, b) => ({              // implicitly returning JS object
   a1: a, b1: b
})

An arrow function does not have its own this. this in arrow functions is always statically defined by the surrounding lexical scope.
In the example below, when using traditional function, this refers to the num object, whereas when using arrow notation, this is pointing to the global object. Arrow functions doesn't have its own this, and so this refers to outer scope, and outer scope for num object is the window object.


Even if I use call() method, result is the same.


In the below example, when using traditional function, this refers to the global object, whereas using arrow function, we get the desired result.


In order to get the greeting message using the traditional function, there are several ways to keep reference to this object inside of setTimeOut function. You can create a self variable like below:

const str = {
    value: 'Delayed greeting',
    greet: function() {
        const self = this;
        setTimeout(function() {
            console.log(self.value);
        }, 2000)
    }
};

str.greet();

or bind with this like below:

const str = {
    value: "Delayed greeting",
    greet: function() {
        setTimeout(
            function() {
                console.log(this.value);
            }.bind(this),
            2000
        );
    }
};

str.greet();

It is not possible to use arrow function expression as a function constructor and create new objects from it.
Share This:    Facebook Twitter

Monday, March 4, 2019

LWC: Fetch picklist values

<!-- fetchPicklistValues.html -->
<template>
    <lightning-card title="WireGetPicklistValues" icon-name="custom:custom67">
        <template if:true={picklistValues.data}>
            <div class="slds-m-around_medium">
                <template for:each={picklistValues.data.values} for:item="item">
                    <lightning-input
                        key={item.value}
                        label={item.label}
                        data-value={item.value}
                        type="checkbox"
                        onchange={handleCheckboxChange}
                    ></lightning-input>
                </template>
            </div>
        </template>
    </lightning-card>
</template>


// fetchPicklistValues.js
import { LightningElement, wire } from 'lwc';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import TYPE_FIELD from '@salesforce/schema/Account.Type';

import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';

export default class FetchPicklistValues extends LightningElement {

    @wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })
    objectInfo;

    @wire(getPicklistValues, {
        recordTypeId: '$objectInfo.data.defaultRecordTypeId',
        fieldApiName: TYPE_FIELD
    })
    picklistValues;

    handleCheckboxChange(event) {
        console.log(event.target.dataset.value);
        console.log(event.target.checked);
    }
}

As per documentation, use getPicklistValues wire adapter (from lightning/uiObjectInfoApi module) to fetch picklist values for a specified field.

Parameters:

  • recordTypeId—(Required) The ID of the record type. Use the Object Info defaultRecordTypeId property, which is returned from getObjectInfo or getRecordUi.
  • fieldApiName—(Required) The API name of the picklist field on a supported object.
  • propertyOrFunction—A private property or function that receives the stream of data from the wire service. If a property is decorated with @wire, the results are returned to the property’s data property or error property. If a function is decorated with  @wire, the results are returned in an object with a data property and an error property.
Find out more about the data inside objectInfo and picklistValues variable:


Share This:    Facebook Twitter

Sunday, March 3, 2019

Lightning Web Components: A Tale of Two DOM's


The shadow DOM is a subtree that branches off the DOM (light DOM). It hides away the complexity of components from the rest of the page. It has actually been around for quite a while. In fact, all of these elements utilize the shadow DOM to hide their complex markup and styling away.

<input type="range" />
<video controls width="250"></video>
<input type="date" />

Because of the new concept of shadow DOM, we need to avoid the confusion between the DOM you knew before and this new shadow DOM. So you are going to see the term light DOM used to describe the DOM you have been familiar with and working with all these years. But before we dive into the shadow DOM, here's one more term, the logical DOM. So the logical DOM is an umbrella term, so the light DOM and shadow DOM together are a part of logical DOM.


To understand shadow DOM, let’s look at the HTML5 <video> element, which is a custom element with a shadow DOM. Because Show user agent shadow DOM is enabled in Chrome Developer Tools, you see the #shadow-root node and its child elements, which make up the shadow DOM. If you disable this option, you would see only the <video> tag, and none of its children.


There are a variety of terms that we need to understand when working with the shadow DOM.
  • Shadow Host: It is the element in the light DOM that is hosting the shadow DOM. So the shadow host, in this case, is the video tag, and it hosts the shadow root.
  • Shadow Root: It is labelled in Chrome dev tools with #shadow-root, and is the root node of the shadow tree, encapsulating a DOM subtree. All this markup within the shadow root is shadow DOM. You can also see a nested shadow tree here, which is also known as a DOM subtree. So one DOM subtree can end up hosting another DOM subtree
  • Shadow Boundary: It encapsulates styling rules that are defined within a given piece of shadow DOM. So in other words, a CSS selector that's applied in the shadow DOM doesn't apply to other elements outside of shadow DOM and vice versa. This is because styles in the shadow DOM do not cross over the shadow boundary. The shadow boundary exists at the shadow root. To clarify, the shadow boundary is a concept and is merely a term used to describe the boundary between the light DOM and shadow DOM.
Creating shadow DOM is a simple 3-step process.
  1. Select shadow host, which is an element in the light DOM that will wrap the shadow root.
  2. Create a shadow root
  3. Add elements to the shadow DOM using the same methods that you use to append elements to the light DOM: innerHTML and appendChild
In the code below, the style is only going to impact the light DOM.

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        h1 { color: red; }
    </style>
</head>
<body>
    <h1>Hello World from the light DOM</h1> 
    <div id="host"></div>

    <template>
        <h1>Hello World from the shadow DOM</h1>
    </template>

    <script>
        var template = document.querySelector('template');
        var host = document.getElementById('host');
        var root = host.attachShadow({mode: 'open'});
        root.appendChild(document.importNode(template.content, true));

        // Only going to get a reference to the light DOM
        console.log(document.querySelectorAll('h1'));

        // Only going to get a reference to the shadow DOM. For multiple pieces of shadow DOM in the page,
        // you need to get the shadow root that is appropriate for the element that you are trying to target
        console.log(root.querySelectorAll('h1'));
    </script>
</body>
</html>

Lightning Web Components

The shadow DOM for a Lightning web component is created automatically. The component author doesn’t have to implement it (no need to use the attachShadow() or appendChild() methods). Also since Lightning web components don’t use the native shadow DOM yet, you can’t view their shadow DOM in Chrome Developer Tools. Even if you enable Show user agent shadow DOM, you don’t see the shadow DOM.

Resources:
https://medium.com/front-end-weekly/the-rise-of-shadow-dom-84aa1f731e82
Share This:    Facebook Twitter

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top