Web Components – 4 connectedCallback

Lets learn about component lifecycle.

following are the callback/api you will need to know 

  1. connectedCallback  – handler
  2. disconnectedCallback – handler
  3. adoptedCallback – handler
  4. attributeChangedCallback – handler
  5. observedAttributes – static getter

use of connectedCallbackHandler: 

generally all the inner HTML for a web component is defined here. below is the example

<script>
    class WebComponentExample extends HTMLElement{
        connectedCallback(){
            this.innerHTML = '<button>click me</button>'
        }
    }
    if(!customElements.get('web-component-example')){
        customElements.define('web-component-example',WebComponentExample);
    }
</script

when does connectedCallback gets called ?

to find this lets remove innerHTML and add an alert in connectedCallback

connectedCallback(){
            alert("in connectedCallback method");
}

now lets add this component to the body of the html

<body>
    <web-component-example></web-component-example>
</body>

now when we reload page, we should bee seeing an alert message.

what will happen when you remove <web-component-example> from body. lets try and check it out.

it turns out that no alert message is shown. but we are registering the component in our script right ? hmm.. whats happening ? lets find out.

lets add a constructor to our web component

<script>
    class WebComponentExample extends HTMLElement{
        constructor(){
            super();
            alert("in constructor");
        }
        connectedCallback(){
            alert("in connectedCallback method");
        }
    }
    if(!customElements.get('web-component-example')){
        customElements.define('web-component-example',WebComponentExample);
    }
</script>

lets refresh our page. nothing happened right ? so to understand better , open dev tools and type

document.createElement("web-component-example");

you should be seeing an alert. so when a component is created, constructor gets called

so when does then connectedComponent is called — its called when component is added to DOM. so to test this, type below code in dev tools

var a =  document.createElement('web-component-example');
document.body.append(a);

so on document.createElement, constructor gets called, when component is added to DOM , connectedCallback is called

connectedComponent vs constructor

main difference to be noted is in constructor, we will not be able to add innerHTML, and use inbuilt methods like getAttributes etc. these are all only available in connectedCallback. see the below example

<script>
    class WebComponentExample extends HTMLElement{
        constructor(){
            super();
            console.log("constructor - attribute value is "+ this.getAttribute('testAttribute'));
        }
        connectedCallback(){
            console.log("connectedCallback - attribute value is "+ this.getAttribute('testAttribute'));
        }
    }
    if(!customElements.get('web-component-example')){
        customElements.define('web-component-example',WebComponentExample);
    }
</script>

as we can see from below, in constructor attribute value is null where as in connectedCallback we were able to see value.

New Journey

I moved to a new company, and its really overwhelming,  and i couldn’t concentrate much on my learning path and was unable to publish any blogs.

I wanted to change this.  from long time i wanted to read Martin fowler’s Refactoring book(First edition!).  and i felt this is the right book to read now and restart by blogging. I really hope i will continue my learning path and to publish blogs as frequently as possible.

 

You Don’t Know Java Script- Up and Going Part 1

Comparison Operators

if I ask you what is result of the following ?

var a = [‘a’ ,’b’, ‘c’];
var b = [‘a’ ,’b’,’c’];
a == b

most probably you would say true right ? But that’s not the case here, the answer is false
let us examine why

when you are using == or === operators for comparing non primitive types, i.e functions or objects including arrays, they will simply check whether the references match, not anything about underlying values.

for example in case of arrays , while comparing , all array values are by default coerced in to strings by joining all values with commas( , ) in between.  consider below example now

var a = [1 ,2 ,3];
var b = [1 ,2 , 3];
var c = “1,2,3”;
a == c;  // will return true

Inequality and Coercion

var a = 41;
var b = “42”;
var c = “43”;
a < b;   // true;
a < c;   // true;

In case of above inequality comparison,

  • when comparing two string values , the comparison is made lexicographic-ally i.e the case with a < b
  • where  as, if any one of the both is not a string then both values are coerced with numbers.

So what will be the result of comparing a Number and a String if both are coerced in to numbers?

var a = 42;
var b = “foo”;
a > b;  //false
a < b;  // false
a == b;  //false

So now what do you think coercion of  “foo” will be ?
its “Invalid Number Value” NAN

And the specification says NAN is neither greater nor less than any other value hence the result is false for the above.

 

 

 

 

 

 

 

Meaningful Names

Names are everywhere in the software. We name our variables, functions, arguments,classes and namespaces. We name our source files and the directories that contain them.So Basically we Name and Name and Name. Because we do so much of it . We’d better do it well. Let is see simple rules for creating good names.

Use Intent Revealing Names

Choosing names takes time but it saves more than it takes. So take care while naming and do change them when you find better ones.Every one who reads your code will be happier(including you) if you do so.This is what you need to think while naming – The name of a variable , function , or a class , should tell you why it exists, what it does, and how it is used.

If a name requires a comment then it does not reveal its content. in the below variable ‘b’ reveals nothing . we should choose a name such that it should specify what is being measured and unit of measurement

int d; //ellapsed time in days
int elapsedTimeInDays;
int daysSinceCreation;
int daysSinceModification;
int fileAgeInDays;

If you follow this your life will become happy. consider if I ask you what the below code does
       public List<int[]> getThem()
        {
            List<int[]> list1 = new List<int[]>();
            foreach(var x in theList)
            {
                if(x[0] == 4)
                {
                    list1.Add(x);
                }
            }
            return list1;
        }
Why do you think its hard to tell what the above code does. 
its not at all complex its just plain 4 lines of code. 
Here the problem is not about the simplicity of the code, but its about the imlicity , meaning, 
the degree to which the context is not explicit in the code itself. with the above code its hard to answer 
the below questions
  1. What kind of things are in theList ?
  2. What is the significance of zeroth subscript of an item in theList?
  3. What is the significance of value 4?
  4. How should I use the list being returned?

I am sure with looking the larger context of the program its very hard to answer the above questions. Now consider the below code after reformatting the above code

public List<int[]> getFlaggedCells()
        {
            List<int[]> flaggedCells = new List<int[]>();
            var STATUS_VALUE = 0;
            var FLAGGED = 4;
            foreach (int[] cell in gameBoard)
            {
                if(cell[STATUS_VALUE] == FLAGGED)
                {
                    flaggedCells.Add(cell);
                }
            }
            return flaggedCells;
        }
Now if you see above code, readability is much better after just applying naming conventions.
And we can go further and create a new class and hide all the magic numbers(4, 0) in that
class as shown below.
 public List<Cell> getFlaggedCells()
        {
            List<Cell> gameBoard = new List<Cell>();
            List<Cell> flaggedCells = new List<Cell>();
            foreach (var cell in gameBoard)
            {
                if (cell.isFlagged())
                {
                    flaggedCells.Add(cell);
                }
            }
            return flaggedCells;
 
        }
As you can see readability is must better now, all the implementation details are abstracted.

Later equals never

if you have been a programmer for more than 2 or 3 years, have you ever been impeded by bad code written by you or your team.? when i say impediment, what i think about impediment is if you were asked to do a change and it ideally should have taken less time, but practically it is never the case, doing small change requires making lot of other changes.

I think this will happen because of bad code. and ofcourse this bad code was written by us the programmers. but why do you think we write bad code? may be because of

we are trying to go fast or we were in a rush ignoring the principles , perhaps we were ignorant or tired of working on program for so long and may be frustrated because of this or promised to your manager to get it done by this time at any cost! or may be something cool coming up and you were pretty excited to get it started so didn’t concentrate on the current task in your hand.

and most of the time you know the program is in a mess and you have choosen to leave it for another day since you might have relieved by your QA confirmed that the code is working.We all have done it. I had done it saying to ourselfs we will come late and clean this up!

There is a law called LeBlane’s law which says ‘Later equals Never’. Now you know the law and its applicable to us

OAuth 2.0… basics you need to know…

OAuth 2.0

Before jumping straight in to oAuth.. let me ask you some questions..(may be rewind yourselfs 2-3 years back..because in the last 2-3 years.. each and every popular site you are interacting with would already have implemented oAuth)

How many have you given passwords of either facebook/gmail/yahoo to other sites like slideshare/zomato etc..
if your answer is yes.. then its a bad thing.. its wrong to share passwords.. you are giving access to slideshare or any other third party application access to your full gmail account.

Necessity and Birth of oAuth

with new applications(mobile/web) growing day by day.. and its mandatory that at some point of time .. we have to register to theapplication.. and to make user’s life easy(by not having remembering new passowrd :D) app providers have provided a way to login via google/facebook/twitter to their applications.this has led to user sharing their username/password of gmail/twitter/facebook to the third party provider..

This is a huge security breach.. consider you have provided your gmail id and password.. third party has access to your entire gmail.. i.e it can post/delete mail with your consent..

So there is a need to register with facebook/gmail/twitter with out having to share username/password..

i believe that need has became developing oAuth

OAuth Definition

Here’s the definition of OAuth 2.0 from the OAuth 2.0 IETF specification itself:
“The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf.”

Terms to Know

1. Resource Server – The Server that holds the resource
2. Resource Owner – The user who owns the specific resources
3. Authorization Server – A server that authenticates the resource owner and issues access tokens to the client
4. client – the application that requests access on resource on behalf of resource owner

IceBergClass -AntiPattern

found some article here

http://deviq.com/iceberg-class/

its a good read… !!

In Short.. its not good to have more PRIVATE methods in your class.
if you have more methods that depends on some behaviour.. its better to have abstracted them. i.e have an interface and declare all your behaviours in the interface and have the class implement this interface.. so that you will abstract the behaviour in to a concrete class and if ever this behaviour were to be changed, you will do changes in the concrete class.. by that way you will be adhering to single responsibility principle and open closed principle