<rss version="2.0">
  <channel>
    <title>Web Atoms Blog</title>
    <description>Interesting blog articles for Developers about general development and web atoms update</description>
    <link>https://www.webatoms.in/blog</link>
    <lastBuildDate>Wednesday, April 29, 2026</lastBuildDate>
    <pubDate>Wednesday, April 29, 2026</pubDate>
    <ttl>60</ttl>
    <item>
      <title>Internet of Things</title>
      <link>https://www.webatoms.in/blog/general/Internet-of-Things-23</link>
      <author>srikanth.naidu</author>
      <description> 
The Internet of Things (IoT) is a network of interconnected physical objects that use sensors, software, and other technologies.

Interconnected computing devices, mechanical and digital equipment, objects, animals, or people having unique identities (UIDs) and the capacity to send data over a network without the need for human-to-human or human-to-computer communication.

Any device that can be assigned an IP address and can transport data over a network, such as a heart monitor implant, a farm animal with a biochip transponder, a car with integrated sensors to notify the driver when tyre pressure is low, or any device that can be assigned an IP address and can transport data over a network, are examples of internet of things objects.
 

 IoT Developed from machine-to-machine (M2M) communication, which involves machines communicating with one another across a network without having to interact in real time. Connecting a gadget to the cloud, administering it, and collecting data is referred to as machine to machine communication.

###History

In 1982, a customised Coca-Cola vending machine at Carnegie Mellon University launched the Internet of Things concept.

###How it works?

IoT devices acquire data by interacting with their surroundings in the real world, and this data is then saved on the cloud.

By connecting to an IoT gateway or other edge device, IoT devices may exchange sensor data that is either transmitted to the cloud for analysis or processed locally.

IoT devices may be interacted with using applications on various devices, such as smartphones.


###Applications

Consumer, commercial, industrial, and infrastructural IoT devices are frequently separated.

 ![image](/api/attachments/att/97/IOT2.png)

###Frameworks

IoT frameworks include the following:

Amazon Web Services (AWS) IoT is an Amazon cloud computing platform for IoT. This framework is intended to make it simple and safe for smart devices to connect to the AWS cloud and other connected devices.

The Azure IoT Suite from Microsoft is a platform that consists of a set of services that allow customers to connect with and receive data from their IoT devices, as well as execute different data operations such as multidimensional analysis.

Brillo/Weave, developed by Google, is a platform for developing IoT applications quickly.

Calvin is an Ericsson-developed open source IoT platform for developing and administering distributed applications that allow devices to communicate with one another.
</description>
      <pubDate>Thursday, December 5, 2024</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/93/iot-2.png</image>
      <guid>https://www.webatoms.in/blog/general/Internet-of-Things-23</guid>
    </item>
    <item>
      <title>Number-Based Video Captcha</title>
      <link>https://www.webatoms.in/blog/general/Number-Based-Video-Captcha-36</link>
      <author>Simmi Kava</author>
      <description>###Number-Based Video Captcha: A New Way to Verify Human

**Introduction:**

In today's digital age, online security has become a paramount concern. As the internet continues to evolve, so do the methods employed by cybercriminals to gain unauthorized access to sensitive information. To counteract this growing threat, NeuroSpeech Technologies Pvt. Ltd. has developed a cutting-edge solution known as Number-Based Video Captcha. In this blog post, we will explore this innovative approach to verifying human users and discuss its potential impact on online security.

**What is Number-Based Video Captcha?**

_Number-Based Video Captcha_ is an advanced technology developed by NeuroSpeech Technologies Pvt. Ltd. that aims to distinguish between humans and bots during online interactions. Traditionally, captcha systems have relied on users to solve visual puzzles or answer simple questions to prove they are human. However, these methods have become susceptible to automated attacks. 

Text-based CAPTCHA often presents challenges for users. The distorted characters or complex puzzles can be difficult to interpret, leading to frustration and discouragement. This can result in users abandoning the process or seeking alternative websites that offer a more user-friendly experience.

Optical Character Recognition (OCR) technology has advanced over the years, making it easier for automated bots to bypass text-based CAPTCHA. Bots can analyze and interpret the distorted characters with a high degree of accuracy, rendering the security measure ineffective against sophisticated attacks.

Image verification CAPTCHA systems often require users to interact with images by clicking on specific objects or areas. However, the interpretation of these images can vary among users, leading to inconsistencies in the verification process. Different users may perceive the same image differently, resulting in false positives or negatives. Image verification-based CAPTCHA relies on a finite set of images that are pre-selected for verification purposes. This limited pool of images can be exploited by bots or attackers who can build a database of these images, making it easier to bypass the security measure. Additionally, the lack of diversity in images can lead to monotony for users, further affecting the usability and engagement.

Also, it often requires users to perform additional mental tasks, such as identifying specific objects or patterns within an image. This can increase the cognitive load on users, particularly those with limited cognitive abilities or language barriers, making it more challenging to successfully complete the verification process. These systems track the movement of the mouse cursor to determine the validity of the user's response. While this method may seem effective in distinguishing humans from bots, it raises several security concerns:

a) Privacy Breach: Mouse location tracking can compromise user privacy by capturing and storing their mouse movements. This sensitive data could be exploited by malicious actors for various purposes, such as targeted advertising, identity theft, or unauthorized tracking.

b) User Profiling: Capturing mouse location data over time allows for the creation of user profiles. This profiling can be used to monitor user behavior, track online activities, and potentially violate user privacy and autonomy.

c) Data Vulnerability: Storing mouse location data on servers poses a potential risk as these data repositories can become targets for cyberattacks. If attackers gain access to these databases, they can obtain sensitive user information, leading to further security breaches.

In addition to mouse location tracking, some image verification CAPTCHA systems also capture keystrokes to verify user responses. This approach introduces its own set of security threats:

a) Keystroke Logging: Keyboard tracking can record all user keystrokes, including sensitive information such as passwords, credit card details, and personal messages. If these data are intercepted or mishandled, users become vulnerable to identity theft and financial fraud.

b) Insecure Data Transmission: Transmitting keyboard tracking data to remote servers may expose it to interception or unauthorized access. This can occur during data transfer, potentially leading to the compromise of sensitive user data.

c) Trust Concerns: Users may be hesitant to enter sensitive information or perform certain actions if they suspect their keystrokes are being recorded. This lack of trust can hinder the usability and functionality of the CAPTCHA system.

Number-Based Video Captcha addresses this challenge by utilizing video-based authentication techniques.

**How does it work?**

Unlike conventional captcha systems, Number-Based Video Captcha presents users with a dynamic video containing a sequence of numbers. The user is then required to correctly identify and enter the numbers displayed in the video. By incorporating video elements, NeuroSpeech Technologies Pvt. Ltd. ensures a higher level of security by making it more difficult for bots to decipher and replicate the video content.

**Key features and benefits:**

1. Enhanced Security: Number-Based Video Captcha offers a robust defense against automated attacks, ensuring that only genuine human users can access protected content or services.

2. User-Friendly: Unlike complex and visually challenging captchas, this technology presents a straightforward and intuitive verification process, making it easier for users to prove their authenticity.

3. Compatibility: The technology seamlessly integrates with existing web applications and platforms, making it a versatile solution for businesses across various industries.

5. Cost-Effective: Implementing Number-Based Video Captcha can significantly reduce the resources required to combat bot attacks, resulting in cost savings for organizations.

**Conclusion:**

Number-Based Video Captcha represents a significant advancement in online security measures. By incorporating dynamic video elements, this innovative solution provides a more effective and user-friendly method to verify human users while deterring automated attacks. As technology continues to evolve, it is crucial to stay one step ahead of cybercriminals, and Number-Based Video Captcha offers a promising solution to enhance online security in the digital era.

PS: Used in [Castyy - Cast Your Talent](https://castyy.com), our growing Social Network for Performing Arts, Film, Media and Entertainment Industry Professionals.
</description>
      <pubDate>Tuesday, August 8, 2023</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/251/Captcha-WebAtoms1.png</image>
      <guid>https://www.webatoms.in/blog/general/Number-Based-Video-Captcha-36</guid>
    </item>
    <item>
      <title>Popup Action button</title>
      <link>https://www.webatoms.in/blog/tutorials/Popup-Action-button-35</link>
      <author>Ajay Singh</author>
      <description>Hello Everyone,

In this article, I will explain how to implement a PopupActionButton in WebAtoms with examples.

####What you will learn?

- You will learn how to implement the PopupActionButton on any of the pages.
- How to display the menu item. 
- What action can be done using this component? 

####Why use it?

- Generally, PopupActionButton is used in `actionRenderer` (a bindable property of the base page) to display some quick menu options.
- On the basis of user selection, you can perform some actions or navigate to other pages.

####How to write code?
````javascript
&lt;PopupActionButton
     icon="fa-solid fa-ellipsis-vertical"&gt;
      &lt;div 
            style-width="80px" 
            data-click-event="none" 
            data-click-animate="no"&gt;
                &lt;MenuItem
                    label="Add"
                    icon="fa-solid fa-add"
                    data-click-event="add-new"
                    /&gt;
                &lt;MenuItem
                    label="Modify"
                    icon="fa-solid fa-edit"/&gt;
                &lt;MenuItem
                    label="Delete"
                    icon="fa-solid fa-trash-can" /&gt;
     &lt;/div&gt;
&lt;/PopupActionButton&gt;;
````

MenuItem is a function that takes some parameters like label, icon, event-click, href, target, etc.

####How to navigate on the menu click?

In the above example, the `data-click-event` attribute calls the `openAddNew` function. Meaning it will navigate to add new training.

````javascript
 @Action({ onEvent: 'add-new' })
  openAddNew() {
    PageNavigator.pushPage(AddNew);
  }
````

####Code Explanation

- We can set the `label` property to display the name of that menu.
- We can associate an `icon` with the menu. In the above example, we have used the `font awesome` icon.
- We can even set the `eventClick` to perform some action. In the above example, this.deleteTraining() is the method that would be executed on clicking the Delete menu item. 
- `href` property can be used to redirect to other pages.

Check out the [StackBlitz Demo](https://stackblitz.com/edit/stackblitz-webcontainer-api-starter-vrfeqi?file=src%2Fpages%2Fhome%2FHome.tsx) here.
</description>
      <pubDate>Monday, May 22, 2023</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/249/webP.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/Popup-Action-button-35</guid>
    </item>
    <item>
      <title>WebAtoms BottomPopup</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms-BottomPopup-34</link>
      <author>Ajay Singh</author>
      <description>Hi Guys,

 In this blog, you will learn how to create a Bottom popup in `WebAtoms`. At the end of this blog, you can get the source code link of this control.

####What is  BottomPopup?
`BottomPopup` is the surface containing additional content that is docked to the bottom of the screen.
They are generally used to keep a feature or secondary content visible on the screen when the content in the actual UI region is frequently scrolled or navigated.

`BottomPopup` is a class component that extends from `AtomControl`. It has one static method called the `show`, which takes parameters, let's say in simple words that if we want to send some value to this `BottomPopup` control, we can send it as a parameter to this `show` method.

####What are the Properties of BottomPopup?

Several properties can be used to simply or dock the content inside the `BottomPopup` control.

`titleRenderer` -  This property helps us to add the title for the `BottomPopup` control.

`headerRenderer` - This property helps us to add the header content to this control.

`closeRenderer` -  This property is used to close the `BottomPopup` control.

`footerRenderer` - This property is used to set the content at the footer of this control.

`barRenderer`  - This property helps to attach the icon of this `BottomPopup` control.


####What is the code snippet of the BottomPopup?

To implement this control, the class must extend from `BottomPopup` class.

````javascript
public async openTrainingBottomPopup() {
        await AddNewTrainingBottomPopup.show({parameters: {
            type: "Training"
        }});
    }
this.titleRenderer = () =&gt; &lt;span text="Add New Training" /&gt;;
this.footerRenderer = () =&gt; &lt;RoundButton text="Add"&gt;&lt;/RoundButton&gt;;
````
We have to define one method in our page &amp; by using the show method of `BottomPopup` control we can open this control &amp; we can pass the parameters while opening the popup page.


####What are the Advantages of BottomPopup?

- `BottomPopup` is the alternative to menus or simple dialogs.
- When this popup slides into the screen, the rest of the screen dims, giving focus to the 
   bottom content.
- It may contain the list, button actions, and other quick menu items.
- `BottomPopup` can also be dismissed by touching the outside of the control.
- This control is very easy to use, it's created with modern web technology.

Click [here](https://www.webatoms.in/play/@web-atoms/sample-b4/1) to view the complete demo.
</description>
      <pubDate>Wednesday, December 14, 2022</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/246/bottompopup4.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms-BottomPopup-34</guid>
    </item>
    <item>
      <title>VSCode Error Lens Extension.</title>
      <link>https://www.webatoms.in/blog/general/VSCode-Error-Lens-Extension-33</link>
      <author>Ajay Singh</author>
      <description> [Error Lens](https://marketplace.visualstudio.com/items?itemName=usernamehw.errorlens) VSCode extension.

Publisher: **Alexander**

This extension shows the error message and highlights the line containing the error while writing the code."
####Features

- Highlight lines containing diagnostics.
- Append diagnostic as text to the end of the line.
- Show icons in gutter (icons like Warning, Error, Info, Hint) on the left side of the VSCode editor.

   ![image](/api/attachments/att/242/demo.png)

- Show message in the status bar.

   ![image](/api/attachments/att/243/1.png)
</description>
      <pubDate>Wednesday, September 28, 2022</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/241/ErrorLens.gif</image>
      <guid>https://www.webatoms.in/blog/general/VSCode-Error-Lens-Extension-33</guid>
    </item>
    <item>
      <title>WebAtoms - DataGrid</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms--DataGrid-32</link>
      <author>Ajay Singh</author>
      <description>####What is DataGrid Control?
A `DataGrid` is a class component that extends from the `TableRepeater` control.   A `TableRepeater` control simply represents the table structure that consists of the table, the header, the body, and the footer.  This control also extends from [AtomRepeater](https://www.webatoms.in/blog/tutorials/WebAtoms--AtomRepeater-30#contextId=0) control.

A `DataGrid` user interface control helps display the information or data in a grid-like format of rows and columns. In this UI control, you can define customized columns and sort orders for each header. A `headerSort` property can be used to specify the order in which columns load. We can add the desc order query by using `headerSortDescending`. 

####What are the properties of DataGrid control?

`orderBy` - This is the two-way data binding, to load any specific column in default order, we can set this property before the top node. 
 

`selectedItems` - Gets the DataGrid's selected items as a collection.

`items`- Gets the items displayed in the `DataGrid`.

`columns`- This property is bound to the array which defines the
header, `headerSort`, `headerSortDescending`, and `labelPath` as properties for const variable of type `IDataGridColumn`.

`SelectAllColumn` - Checkboxes are added to all columns in the control with this property.


One great benefit is that `AtomRepeater` properties can also be used here.
Other than `columns`, all properties are bindable properties.

####Code snippet of DataGrid Control?

```javascript
 &lt;DataGrid
       for="table"
       style-width="100%"
       allowMultipleSelection={true}
       items={Bind.oneWay(() =&gt; this.ViewModel.ProductList)}
       columns={columns}
                /&gt;
```

####How to define the columns? 
In the code, we define the array of objects of type `IDataGridColumn`.

```javascript
  const columns: IDataGridColumn[] = [
            SelectAllColumn,
            {
                header: "Title",
                labelPath: (item: IProduct) =&gt; item.title
            },
            {
                header: "Brand",
                labelPath: (item: IProduct) =&gt; item.brand
            },
            {
                header: "Category",
                labelPath: (item: IProduct) =&gt; item.category
            },

        ];
```

We have set the `columns` property of `DataGrid` to this const property which is the type of `IDataGridColumn`. It provides us to select all columns if we mention the SelectAllColumn value inside the array. Adding a checkbox to each row in the "DataGrid" will let you perform single or multiple operations.

Header means the heading of the column
`labelPath` is used to display the text
`headerSortDescending` will sort the column in descending order.

####Advantages of DataGrid Control?
- In addition to auto-generating columns, it also provides sorting properties (by default ASC) and allows setting the order in desc.
-  It is easier to understand this control due to its less code approach, and the order definition and column definition are separated.
- The separation of concerns approach makes maintenance easy.
-We can use the repeater control properties since this control extends `TableRepeater`.
- Since this control is very lightweight and is based on the latest technology, it doesn't require the installation of any additional npm packages.


</description>
      <pubDate>Monday, September 19, 2022</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/240/DataGrid.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms--DataGrid-32</guid>
    </item>
    <item>
      <title>WebAtoms - AtomRepeater Drag &amp; Drop</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms--AtomRepeater-Drag--Drop-31</link>
      <author>Ajay Singh</author>
      <description>In this article, we will learn the Drag &amp; Drop in AtomRepeater, and also understand its implementation with the help of examples. 
Dragging and dropping allow moving an object to a different location. It is an interactive and user-friendly concept.

It allows the user to click and hold the mouse button over an element, drag it to another location, and release the mouse button to drop the object. 
HTML 5 Drag and Drop are much easier to code. Any element in it is draggable.

In traditional HTML, to implement the drag &amp; drop features, the developer had to write complex JavaScript code or use other JavaScript frameworks like jQuery, etc.

HTML5 came up with the [drag &amp; drop API](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API), which makes it easier to use in complex UI.

Before proceeding further, I suggest you read the [blog](https://www.webatoms.in/blog/tutorials/WebAtoms--AtomRepeater-30#contextId=2) on WebAtoms AtomRepeater UI control. The blog explains the AtomRepeater control with an example. It helps to understand this blog more conveniently.

Let's extend the article’s example, where we have shown the top cities of the world. Now, we will enable the end-user to re-order their favorite city by dragging the city from top to bottom or in an order of their choice. 

####Code snippet for Drag &amp; Drop?

```javascript
&lt;AtomRepeater
     class="row-span-2 column-span-3"
     items={Bind.oneWay(() =&gt; this.viewModel.agencyLocations)}
     enableDragDrop={true}
     itemRenderer={(item: IAgencyLocation) =&gt;
     &lt;Row 
         draggable={true} class="item"&gt;
          &lt;i 
             class="fa-solid fa-arrows-up-down-left-right fa-2x1"&gt;
          &lt;/i&gt;
          &lt;div 
             type="text" 
             text={item.location} 
             class="location"&gt;
           &lt;/div&gt;
     &lt;/Row&gt;
        } /&gt;

```

In the example, we first added the `enableDragDrop` property and set it to true. We have made the draggable attribute `true` on the element we want to drag to another place.

####The benefit of the AtomRepeater Drag &amp; Drop feature.

One of the greatest advantages of drag-and-drop is its simplicity.

 In the example, we have shown you the reorder list. We can reorder or drag the photo gallery, which makes it easier to arrange the picture in a suitable way.

 We don't require any other JavaScript framework or npm modules to implement the Drag &amp; Drop.
</description>
      <pubDate>Thursday, July 14, 2022</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/239/AtomRepeaterDD1.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms--AtomRepeater-Drag--Drop-31</guid>
    </item>
    <item>
      <title>Expander</title>
      <link>https://www.webatoms.in/blog/tutorials/Expander-2z</link>
      <author>Shubham Khare</author>
      <description>#### WebAtoms Expander

This article explains Expander control in detail and highlights a way to implement this control which is present in the [WebAtoms](https://www.webatoms.in/index.html#contextId=0) framework. The `Expander` is the user interface control imported from the WebAtoms library.

#### What is Expander control?

WebAtoms Expander is the functional component. For implementing the `Expander` control, there is no need to extend it into our class component. It helps in easy implementation of the layout, which is needed to expand and collapse, which can help add multiple interacting options on a single screen.

#### Properties of Expander control

- `icon` - icon is a string property used in assigning the icon code or path name. It is an optional property utilized for enhancing the layout by displaying icons.

- `isExpanded`- isExpanded is a boolean property that expands the form layout when set to true and collapses when set to false. By toggling the `isExpanded` property, we can expand or collapse the view on some DOM event.

#### How to implement the Expander control?

In this example, we will use the `Expander` control to display a form in separate sections where each section is a separate `Expander`, shown separately in the _ExpanderDemoScreen_.

**Code for ExpanderDemoScreen**

In this example, we will create three simple forms inside an `Expander` where each `Form` in the `Expander` has unique user fields. The layout of the screen only allow one `Form` to display at a time.
When one `Form` is in an expanded state, the other two remain collapsed.

![image](/api/attachments/att/210/Expander-Demo-Screen1.png)

![image](/api/attachments/att/211/Expander-Demo-Screen2.png)

![image](/api/attachments/att/212/Expander-Demo-screen3.png)

**Code snippet for css of ExpanderDemoScreen**

![image](/api/attachments/att/213/Expander-css.png)

**Code snippet for ExpanderDemoViewModel**

The logic for implementing desired expand and collapse behavior.

![image](/api/attachments/att/214/Expander-Demo-Screen-ViewModel.png)

#### Advantages of Expander

- `Expander` control helps create layouts having a master-detail flow. Mainly beneficial when there is a requirement for implementing single-page applications.

- We can generate dynamic layouts, as `Expander` gives us control over the view displayed when a particular event has occurred.

- An `Expander` control is beneficial when there is a requirement of showing only a part of a large layout at a time, making it efficient in small screen sizes.

- The `Expander` control is a lightweight and responsive control.

- 'Expander' can be expanded or collapsed without defining any event.

- As 'Expander' is a functional component hence it is reusable and gets initialized in the constructor of the class component.</description>
      <pubDate>Monday, June 27, 2022</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/236/ExpanderGIF9.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/Expander-2z</guid>
    </item>
    <item>
      <title>WebAtoms - AtomRepeater</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms--AtomRepeater-30</link>
      <author>Ajay Singh</author>
      <description>This article explains AtomRepeater repeater control in detail and highlights a way to bind the data to this control.

####What is AtomRepeater control? 

Without initially understanding what event bubbling &amp; event capturing in javascript is, it may be challenging to understand this control. Event bubbling means whenever an event occurs on an element, like button, p, span, div, or any other HTML element, the event handler will initially run on it and then on its parent and finally up to its other predecessors. For more information about event bubbling and event capturing, please go through this [article.](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_bubbling_and_capture)

WebAtoms AtomRepeater control is the class component that extends from AtomControl.(AtomControl class represents UI Component for a web browser.) AtomRepeater is a data Bind Control, which works as container control. This control displays a repeated list of items bound to this control. A database table, array of objects, or any other list can be attached to this control.

The WebAtoms AtomRepeater control provides a wide range of properties and events.

####What are the properties of AtomRepeater control?

`allowMultipleSelection`- Using this property we can enable or disable the multiple selection functionality.

`items` - This control returns items displayed in this control.

`selectedItems` - To retrieve a collection containing all selected items in a multiple-selection AtomRepeater, use the SelectedItems property.

`valuePath` -This property specifies the path to the property that determines the value of the selectedItem property.

`enableDragDrop` - When you want to grab an object and drag it to a different location, set this property to true.

`itemRenderer` - The itemRenderer property is like an HTML template that decorates and binds the item.

 All of the above properties are bindable properties.

####What is the default event of AtomRepeater?

`event-item-click` - This event fires action when the AtomRepeater control is clicked.

`event-item-select` - This is helpful when we have a requirement to execute any event on the selection of any particular item in the list e.g. trigger an event on the selection of a particular checkbox and so on.

`event-item-deselect` - This is helpful when we have a requirement to execute any event on deselection of any particular item in the list e.g. trigger an event on de-selection of a particular checkbox and so on.

####How to implement AtomRepeater?

```javascript
&lt;AtomRepeater
    items={Bind.oneWay(() =&gt; this.viewModel.agencyLocations)}
    itemRenderer={(item: IAgencyLocation) =&gt;
    &lt;Row&gt;
      &lt;span text={item.location} style-width="75%" /&gt;
        &lt;FAButton
            icon="fad fa-trash-can fa-lg red"
            text="Delete"/&gt;
     &lt;/Row&gt; } /&gt;
```
In the above code, We have to bind the items property, which will be collections or arrays. The itemRenderer property renders the array item.

####How to create an event on an element?

Let's take the above example, where we showed a list of locations. Now we will add the delete function to remove the particular item from the list of locations items. We have to add the data client event attribute to the button.

####How to add the data-click-event? 

```javascript
&lt;FAButton
 	data-click-event="delete-location"
	 icon="fad fa-trash-can fa-lg red"
	 text="Delete" /&gt;
```

The `data-click-event` attribute is not attached to the button. `delete-location` is the value of that data attribute. Now you are thinking, what is the use of this data attribute to the button element? How does this help us to remove the specific location? You are thinking that without calling any HTTP DELETE request will it remove a location item from the list?

We will answer all your questions with an explanation.

The data-* attribute helps us store custom data private to the page or application. This data*-attribute gives us the power to embed custom data attributes on all HTML elements. Here we are embedding the delete-location as the value of this data attribute.

######Confusing?

```javascript
&lt;AtomRepeater
    items={Bind.oneWay(() =&gt; this.viewModel.agencyLocations)}
    event-delete-location={(e: CustomEvent&lt;IAgencyLocation&gt;) =&gt;
      		this.viewModel.deleteAgencyLocation(e.detail)}
    itemRenderer={(item: IAgencyLocation) =&gt;
     &lt;Row&gt;
        &lt;span text={item.location} style-width="75%" /&gt;
           &lt;FAButton
               data-click-event="delete-location"
               icon="fad fa-trash-can fa-lg red"
               text="Delete" /&gt;
     &lt;/Row&gt;}
    /&gt;
```

Notice the event-delete-location attribute of AtomRepeater. We have added the `data-click-event` attribute to the button. And we are using the custom value of this attribute to create the event for the repeater control.

This will helps to bind the event to the AtomRepeater to remove the location.
But how does the location get removed? Whenever the button gets clicked, this event-delete-location event gets triggered. It will send the delete request to the server to remove the specific record from the list of items.

What are the advantages of this control?
 - The first advantage of this control is that we are not binding the location name using the binding. `one-way`, `two-way` &amp; `one-time` binding will not work inside the itemRenderer. There are no binding functions attached to this HTML tag.
- The second advantage of this control is that we are not binding any event to the button, which again helps us load the all-button element quickly in the browser.
- Here we have a single event to the control for a specific operation. (like here is the delete location).
- This control is straightforward to implement and loads the data faster and smoother.

The most important benefit of this control is that we have created only one event at the root level. This will reduce the event listener count in the performance monitor. 
[](add link here)![image](/api/attachments/att/234/performanceListener.png)

Check the JavaScript event listeners count. It indicates that there is a significantly less number of event listeners used in the entire application.
See the event listeners count of popular social media (Twitter) web applications.

![image](/api/attachments/att/237/twitterEventListenerCount.png)

Less event listening leads to less memory usage.

Event rewriting is possible because of the event bubbling of HTML.</description>
      <pubDate>Thursday, June 16, 2022</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/235/AtomRepeater3.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms--AtomRepeater-30</guid>
    </item>
    <item>
      <title>WebAtoms Form - Part || (with upgrades)</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms-Form--Part---with-upgrades-2x</link>
      <author>Ajay Singh</author>
      <description>
 In the [previous article] (https://www.webatoms.in/blog/tutorials/WebAtoms--Form-2r#contextId=0) we have seen what is `WebAtoms Form`. If you haven't seen it, I strongly recommend reading that article.

Today, we will highlight further enhancements and development made to this component.

 Applications use forms to enable users to log in, update a profile, enter sensitive information, and perform many other data-entry tasks. 

`WebAtoms` provides two different approaches to handling user input through forms and without forms.
Let's learn how to build a small screen without the `Form` component.

####Form without Form component?

```javascript
&lt;FormField
     label="Name: "
     required={true}
     error={Bind.oneWay(() =&gt; this.viewModel.errorContact)}&gt;
     &lt;input
        type="text"
        value={Bind.twoWaysImmediate(() =&gt;
                this.viewModel.model.firstName)}
        placeholder="First Name" /&gt;
&lt;/FormField&gt;
&lt;FormField
     error={Bind.oneWay(() =&gt; this.viewModel.errorEmail)}
     label="Email Address:"
     required={true}&gt;
     &lt;input
         type="text"
         value={Bind.twoWaysImmediate(() =&gt; 
         this.viewModel.model.emailAddress)} /&gt;
&lt;/FormField&gt;
&lt;CommandRow&gt;
   &lt;FAButton
        icon="fad fa-plus"
        eventClick={Bind.event(() =&gt; this.viewModel.save())}
        text="Save" /&gt;
&lt;/CommandRow&gt;
```

**ViewModel** validations and save button code sample is as shown below:-

```javascript
@Validate
    public get errorContact() {
        return this.model.firstName ?
         "" : "First name is required";
    }

@Validate
   public get errorEmail(): string {
      const em = (this.model.emailAddress)?.trim();
      if (!em) {
         return "Email address cannot be empty";
       }
      if (em.includes(" ")) {
           return "Email address cannot contain space";
       }
      if (!em.includes("@")) {
           return "Invalid email address";
       }
      return "";
   }
@Action({ validate: true })
    public async save() {
      // save api
    }
   
```

The code snippet explains how to get an alert text message (in red color) underneath the input box when running this code in the browser. The get method helps us write multiple validations. 
The important points to keep in mind while working with `FormField` without adding the Form component.

- We must define the get method with the `@validate` attribute in the ViewModel.
- We don't have to enclose FormField inside the Form component.
- The save button click event must have the @Action attribute with the validate property to true. This will trigger the `ViewModel` validations before actually firing the button event and report errors (if any) to the user.

 - The `required` attribute of `FormField` must be set to true.

Now let's discuss the improvements/enhancements in the form components.

####How to use the Form with eventSubmit and data-event?

```javascript
&lt;Form eventSubmit={Bind.event(() =&gt; this.viewModel.save())}&gt;
 &lt;FormField
    label="Name: "
    required={true}
    error={Bind.oneWay(() =&gt; this.viewModel.model.firstName ?
     "" : "First name is required")}&gt;
    &lt;input
        type="text"
        value={Bind.twoWaysImmediate(() =&gt; 
           this.viewModel.model.firstName)}
        placeholder="First Name" /&gt;
 &lt;/FormField&gt;
 &lt;FormField
    error={Bind.oneWay(() =&gt; this.viewModel.model.emailAddress ?
    "" : "Email address is required")}
    label="Email Address:"
    required={true}&gt;
   &lt;input
       type="text"
       value={Bind.twoWaysImmediate(() =&gt; 
         this.viewModel.model.emailAddress)} /&gt;
   
 &lt;/FormField&gt;
&lt;CommandRow&gt;
  &lt;FAButton
      icon="fad fa-plus"
      data-event="submit"
      text="Save" /&gt;
  &lt;/CommandRow&gt;
&lt;/Form&gt;
```

- Every `FormField` and submit button must be inside the Form component.
- We can define the inline error validations in the TSX file.
- In this case, we will not use the @validate attribute on the method.
  The form component must have the `event submit` property to bind the event.
- Our button must have the `data-event` attribute to submit the `Form`. Like data-event="submit". The value submit is not case-sensitive.

####How to Add multiple Forms?

 you can't nest forms on a single page. You can't nest `forms` because then the `forms` aren't able to identify which fields are for what.

But, sometimes client design demands the use of multiple forms. For E.g. we may have details to be filled up in multiple tabs or sections like phone number sections, Addresses sections, and formal detail sections.


In this case, we can have multiple forms with a single submit button.

####How to write code for multiple Forms?
```javascript
&lt;AtomToggleView&gt;
&lt;ToggleView&gt;
	&lt;Form&gt;Basic Form &lt;/Form&gt;
&lt;/ToggleView&gt;
&lt;ToggleView&gt;
	&lt;Form&gt;Phone number Form &lt;/Form&gt;
&lt;/ToggleView&gt;
&lt;ToggleView&gt;
	&lt;Form&gt;Address Form &lt;/Form&gt;
&lt;/ToggleView&gt;
&lt;/AtomToggleView&gt;
````

####How to define the validation in multiple Forms?

```javascript
&lt;FormField
     error={Bind.oneWay(() =&gt; 
                this.viewModel.errorContact)}
     label="Contact:"
     required={true}&gt;
       &lt;input 
            type="text"
            value={Bind.twoWaysImmediate(() =&gt; 
                        this.viewModel.model.contact)}&gt;
              &lt;/&gt;
&lt;/FormField&gt;
```

We need to define all validations (Basic, phone number, address validation) in ViewModel.

```javascript
  @Validate
    public get errorContact(): string {
        return this.model.firstName ?
         "" : "First name cannot be empty";
    }
```
The above get method allows us to validate the input field.

We need to keep in mind that the Submit button should be outside the forms. meaning we should have a single button  client event (submit) for all the multiple Forms

```javascript
 &lt;FAButton
        class="next-button"
        text="Save"
        eventClick={Bind.event(() =&gt;
         this.viewModel.save())}
                    /&gt;

@Action({ validate: true })
    public async save() {
        this.model = await this.contactService.save(this.model);
        this.close(this.model);
    }
```
####Summarization.
 - We can also get the error messages without encapsulating the FormField inside the Form Component. We have to define the validation error in ViewModel, and the button must have the `eventClick` to submit the form. 
- If we define the inline error messages, they will get fired as soon as the forms get loaded.
- When we are encapsulating the FormField inside the Form component, We have to bind the `eventSubmit` event of the form.  (like save update delete edit operation). The button should be inside the Form component. It must have the `data-event` attribute to submit.
</description>
      <pubDate>Sunday, May 29, 2022</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/209/updatedForm2.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms-Form--Part---with-upgrades-2x</guid>
    </item>
    <item>
      <title>PopupWindow</title>
      <link>https://www.webatoms.in/blog/tutorials/PopupWindow-2y</link>
      <author>Shubham Khare</author>
      <description>####WebAtoms - PopupWindow


This article will cover the popup window in [WebAtoms](https://www.webatoms.in). Today we will learn about implementing a popup window.


####What is a Popup window?


Pop up window is a user interface window displayed in the foreground of a screen. The appearance of the popup window can be controlled programmatically with the help of events.


####Why PopupWindow control?

[WebAtoms](https://www.webatoms.in) provides a simple way of implementing a popup window with features for creating a custom window. With the help of `PopupWindow` control, we can add forms, lists, editors, etc., to the window.

`PopupWindow` is a class component that extends from `AtomControl`. To apply this control, we have to `extend` the component class from `PopupWindow`. Html or JSX inside the `render()` method will be displayed inside the popup with all the styles and click events.

####What are the properties of PopupWindow control?

- `title` - It is a property that allows the user to set the title at the top of the window.

- `showWindow()` or `showModal()` - It's a static function that displays the window that allows the user to display the window when called. It also has parameters that are useful for passing data between screens.

- `close()` - It is a function that closes the window when called.

- `titleRenderer` - It is a property that allows the user to customize the header with Html or JSX tags instead of a plain title.

![image](/api/attachments/att/206/title-renderer-5.png)

#### Implementing PopupWindow

For implementing the `PopupWindow` control, we will first create a class with the name _PopupWindowDemo_ which will be the extension of `PopupWindow`.

**Code snippet for PopupWindowDemo**

![image](/api/attachments/att/188/pop-up-window-demo-2.png)

**Adding style**

![image](/api/attachments/att/203/pop-up-window-demo-style-4.png)

****

For this example, we will create a simple screen (_PopupWindowScreen_) with a button when it's clicked, will call the method `showWindow()`, and the popup will appear on the screen. 

**Code snippet for PopupWindowScreen**

![image](/api/attachments/att/190/pop-up-window-screen-2.png)

Both `showModal()` and `showWindow()` can be used to display the window.

**Adding style**

![image](/api/attachments/att/204/pop-up-window-screen-style-4.png)

****

####Advantages of PopupWindow control?

 - This control renders the existing view inside the window by only using `extend` keyword with `PopupWindow`.

 - The window can be customized in multiple ways with the help of provided render properties, giving more control over the user interface.

 - `PopupWindow` is also draggable, which is beneficial while working with multiple windows on the screen.

 - We can open or close the window programmatically, which helps display or close the window during the click, hover, or any event.

 - We can also create alert or confirmation dialog windows using `PopupWindow`.

</description>
      <pubDate>Thursday, May 19, 2022</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/205/window-pop-up-gif.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/PopupWindow-2y</guid>
    </item>
    <item>
      <title>Regular Expressions (Regex)</title>
      <link>https://www.webatoms.in/blog/developer-guide/Regular-Expressions-Regex-2v</link>
      <author>Shubham Khare</author>
      <description>
###What are Regular Expressions?

In this article, we are about to learn about programming fundamental Regular expressions, also known as regex. It is a powerful tool used for finding patterns and text in a document, sentence, or database.

It is similar to the search-replace feature used in word documents, except regex is much more precise and powerful to edit code and verify user input which is pattern sensitive, for example, email addresses, phone numbers, passwords, etc.

Before that, we need to learn about the characters of regex.

****

###Characters of Regex

- Modifiers
- Metacharacters
- Quantifiers
- Groups and ranges

**Modifiers**

Modifiers are optional characters used to perform case-insensitive and global searches.

| Modifier | Description                                                     |
|:--------:|-----------------------------------------------------------------|
| g        | It performs global matching and returns all the matched results |
| i        | It performs case-insensitive matching                           |
| m        | It performs multiline matching                                  |

**Metacharacters**

In regex, metacharacters are the characters that have special meaning. Metacharacters are written before by a backlash and have a special meaning to a combination.

| Metacharacters |                    Description                    |
|:--------------:|:-------------------------------------------------:|
|        .       | finds a single character                          |
|       \d       | finds a digit character                           |
|       \D       | finds a non-digit character                       |
|       \b       | finds a match at the beginning/end of a word      |
|       \B       | finds a match NOT at the beginning/end of a word  |
|       \f       | finds a form-feed character                       |
|       \n       | finds a newline character                         |
|       \r       | finds a carriage return character                 |
|       \s       | finds any whitespace character                    |
|       \S       | finds any non-whitespace character                |
|       \t       | finds a tab character                             |
|       \v       | finds a vertical tab character                    |
|       \w       | finds a word character                            |
|       \W       | finds a non-word character                        |

**Quantifiers**

Quantifiers specify how many instances of a character, group, or character class must be present in the input for a match.

| Quantifiers |                          Description                         |
|:-----------:|:------------------------------------------------------------:|
|      a*     | matches any string that contains ‘a’ zero or more times      |
|      a+     | matches any string that contains at least one ‘a’            |
|      a?     | matches any string that contains ‘a’ zero or one time        |
|     a{n}    | matches any string that contains ‘a’ exactly n times         |
|    a {n,}   | matches any string that contains ‘a’ at least n times        |
|    a{n,m}   | matches any string that contains ‘a’ between n to m times    |
|      a$     | matches any string that ends with ‘a’                        |
|      ^a     | matches any string that has ‘a’ at the beginning.            |
|     ?=a     | matches any string that is followed by a specific string ‘a’ |
|     ?!a     | matches any string that is not followed by a string ‘a’      |

The quantities ‘n’ and ‘m’ are integer constants, and ‘a’ can be any character or a string.


**Groups and Ranges**

Regex allows us to match the text and extract information for further processing by defining a group of characters enclosed in the parentheses ‘( )’.

Any pattern inside the parentheses will be called a group. For defining the range, denoted by square brackets, e.g. -  [a-z] includes every small case alphabet from a to z.

| Groups |                            Description                           |
|:------:|:----------------------------------------------------------------:|
|  [xyz] | finds any character between the square brackets                  |
| [^xyz] | finds any character excluding the characters inside the brackets |
|  [0-9] | finds a character, which  is a digit in the given range          |
| [^0-9] | finds any character which is not a digit in the given range      |
| (x\|y) | finds any of the given alternatives                              |

****

###Applying the regex

One of the most commonly known uses of regular expressions is for checking if the input string follows a given pattern or not.

The most widely known problem that requires the user to enter a string that must follow strict rules to be accepted by the program is while entering an email id and password.

First, we need to set the rules for each of the inputs.

 **Validation of email ID**

  - The string before the ‘@’ symbol should be a valid combination of alphabets, digits, or a dot, [a-zA-Z0-9.] + @

  - The string after the ‘@’ symbol should also be the valid combination of alphabets, digits, followed by a dot, [a-zA-Z0-9.]

  - The string after the dot should be a string consisting only of alphabets no more than four characters, [a-z]{2,4}.

Regular expression for the given requirements should be 

&gt; _‘^[a-zA-Z0-9.]+@[a-zA-Z0-9.]+\.[a-z]{2,3}$’_

![image](/api/attachments/att/171/emailregex2.png)

 **Validation of password**

  - The password should at least have an uppercase character (?=.*[A-Z]).
  - The password should at least have a lowercase character (?=.*[a-z]).
  - The password should at least have a digit (?=.*[0-9]).
  - The password should have one of the special characters (?=.*[!?@#$%^&amp;*-]).
  - The password should have a minimum of 8 characters, .{8,}.

A regular expression for the given requirements should be 

&gt; _‘^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!?@#$%^&amp;*-]).{8,}$’_

![image](/api/attachments/att/172/passwordregex2.png)

**Search and Replace**

We can use regex patterns for editing multiple lines of code, given that all the lines of code follow the same search pattern, every matched line will be replaced at once.

Suppose if we have a multi-line code with any line that follows the same given pattern.

 ![image](/api/attachments/att/170/searchcode.png)

In the given code we have to replace every `&lt;div&gt;` with a `&lt;li&gt;` and `&lt;/div&gt;` with a `&lt;/li&gt;` without replacing the content written in between the tags.

 - The pattern we are looking for starts with `&lt;div&gt;` tag, followed by an asterisk (*) and a capture group that matches with everything which is not a &lt; symbol of a closing div tag.

 - Regex for the search pattern should be `&lt;div&gt;\*([^&lt;]+)&lt;/div&gt;`

 - When the line that matches with the above pattern we will replace it with `&lt;li&gt;` and `&lt;/li&gt;` tags and keeping the contents that matches with the capturing group intact.

 - Regex for the replace pattern should be `&lt;li&gt;$1&lt;/li&gt;`

 - In the above expression `$1` denotes the first capturing group that matches with everything that is not a &lt; symbol, written as [^&lt;] and it has to match this token as many times as possible after the asterisk symbol denoted by the + operator.


    ![image align = "center"](/api/attachments/att/167/search-replace.png) 


Result after applying both search and replace patterns in vs code.

![image](/api/attachments/att/168/carbon.png)

****

###Benefits of Regex

  - Regex is used in many popular programming languages and has a similar syntax and writing style, making regex universal.

  - Using regex makes the code efficient because the regex pattern is nothing but a string and can be used multiple times for searching patterns.

  - A programmer can code a lot of operations without creating any special functions for each one. Only slight changes in pattern string are required, and a completely different pattern is in use.

  - Regex is very compact and language-independent. For the same operations, the same pattern is enough.

  - Regex also increases the speed of validations by eliminating the use of conditional operators.
</description>
      <pubDate>Friday, April 15, 2022</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/165/rgx3.gif</image>
      <guid>https://www.webatoms.in/blog/developer-guide/Regular-Expressions-Regex-2v</guid>
    </item>
    <item>
      <title>WebAtoms - FileUploader</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms--FileUploader-2w</link>
      <author>Ajay Singh</author>
      <description>This article will cover the file upload control in [WebAtoms] (https://www.webatoms.in/index.html#contextId=0). Today we are heading to understand how to build or implement a file uploader.

#####Why HTML File Upload?
To understand the WebAtoms FileUploader, first, we need to go back to check how to upload the file in simple HTML and JavaScript.
We have to add the input tag with a file type, and on the `onChange` event we can obtain the uploaded files data. This HTML input allows us to open the file explorer and upload the files to our systems or applications.

#####Why WebAtoms FileUploader control?
The above HTML file uploader is not easy to style. Even we cannot change the content of the button. HTML File uploader is the default file uploader that doesn't look attractive. We don't see this uploader in modern web applications.

On another side, WebAtoms has introduced the FileUploader user interface control. FileUploader is a class component that extends from [AtomControl](https://github.com/web-atoms/core/blob/es5/src/web/controls/AtomControl.ts). This control solves the stylistic issues and adds new attributes and methods to help you develop a better user interface experience for file upload.

##### What are the properties of FileUploader control?

`multiple` - Allow the user to select multiple files from file explorer.

`uploadLabel` - Allow the user to change the label of upload control.

`fileFilter` - Allow the user to filter the type of file to upload.

`isDisabled` - Allow the user to disable the upload.

`fileFilterMessage` - Allow the user to show the custom message based on the file filter attributes.

##### What are  the events of FileUploader control?

`eventUploadFinish` - Event fired when file upload is complete.

`eventUploadClick` - Event fired when the page is loaded.

`eventUploadSelect` - Event fired when a file has been selected for an upload operation.

`eventUploadStart` - Event fired when uploading of file has started.

#####Code Snippet?

````javascript
 &lt;FileUploader
                uploadLabel="Upload Button"
                eventUploadFinish={Bind.event((s, e) =&gt;
 this.addFiles(e.detail))}
            /&gt;
````
In the above code snippet, We have shown how to implement the FileUploader control.
The `uploadLabel` property enables us to caption the control as per user requirement.


The `eventUploadFinish` event occurs when the file is uploaded successfully. It will call the `addFiles` method with the file details as parameters. After that, we can send the file to a backend via an HTTP POST call.

#####How to upload the Multiple Files?
````javascript
 &lt;FileUploader 
                uploadLabel="Upload Button" 
                multiple={true}
                eventUploadFinish={Bind.event((s, e)
                =&gt; this.addFiles(e.detail))}
            /&gt;
````
By default, the browser file selection dialog will allow the user to select only one file for upload.

Adding property `multiple` and making it true, enables us to upload the multiple files.

##### Advantages of WebAtoms FileUploader control?

- The very first benefit of using WebAtoms FileUploader helps us to rename the content of the upload Button using the `uploadLabel` property.

 - This control has the inbuild progress bar attached to it, which is visible only while the upload file is still in progress.

- The Cancel button is visible both during the upload process and after the file upload process is complete.

- This control provides many properties which enhance the user experience. In some scenarios, we need to disable the upload, for that we need to simply set the isDisabled property to true.

- The other significant advantage of using this WebAtoms `FileUploader` control is to restrict the user to upload a file of a certain type.
For instance, in some scenarios, we need to upload only the image file, we can achieve this by using the `fileFilter` properties. 
 
- We can also send warning message to the end-user using `FileFilterMessage` property of this control.
 
- According to the requirements, we can transform the style of this control.
This control is built using modern web technologies using JavaScript and HTML. This control is very lightweight in nature and very straightforward to implement.

</description>
      <pubDate>Tuesday, April 5, 2022</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/161/FileUPload.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms--FileUploader-2w</guid>
    </item>
    <item>
      <title>WebAtoms -DropDown</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms-DropDown-2t</link>
      <author>Ajay Singh</author>
      <description>This article provides you with the first experience of writing the simple WebAtoms DropDown user interface control.

####What is WebAtoms?
[WebAtoms](https://www.webatoms.in/index.html#contextId=0) is an advanced MVVM framework to write cross-platform applications in HTML5 and Xamarin.Forms.

####What is DropDown Control?
WebAtoms DropDown control is a class component, that extends from [AtomRepeater](https://github.com/web-atoms/web-controls/blob/dev/src/basic/AtomRepeater.tsx) control. When we click on the control, it opens the window, which has the input field. This control returns the suggestions list based on the character entered by the user and allows us to select the item from the suggestions.

####What are the properties of DropDown Control?

- items 
- match
- value
- labelPath
- valuePath
- suggestionRenderer

The above properties are bindable.

####Let's understand the properties.

To enable hints or applicable values, first, we need to populate the data. We will bind the `items` property of this control that helps us get the suggestions.

`match` property matches the character or text entered in the input field.

`value` property is a two-way binding property that eventually helps us send the selected or chosen data from the list to our database.

`SuggestionRenderer` property helps us to decorate and beautify the suggestions list.

####How to implement the DropDown Control?

Let's understand with a simple example. We want to allow the user to select the country with the ISD code.

```javascript
&lt;DropDown
     items={Bind.oneWay(() =&gt; this.viewModel.countriesList)}
     valuePath={(item) =&gt; item?.isdCode}
     labelPath={(item) =&gt; 
         `${item.countryCode} +${item.isdCode}`}
         match={(text) =&gt; {
         text = text.toLowerCase();
         return (item: ICountry) =&gt;
         item.countryName.toLowerCase().includes(text);}}
     value={Bind.twoWays(() =&gt;
                  this.viewModel.isdCode)}
    suggestionRenderer={(item: ICountry) =&gt;
     &lt;div text={`${item.countryName} +${item.isdCode}`}/&gt;}
                        /&gt; 
```


In the code snippet, we have populated the list of countries and bound it to the items property of this control. 

`LabelPath` shows the label. In the above case, it is the Country code and the ISD code.

`match` property will return the items based on the country name entered by the user. The best thing is that we can search for more than one property. For example, we can also match the currency name, country type, etc.

Last but not least, The `suggestionRenderer` property works as an HTML template that decorates and binds the item. In the above code snippet, we have shown the Country name and the ISD code as a suggestion.

####What is the benefit of DropDown Control?

- This control is very lightweight and straightforward to implement.
- We don't require any  NuGet package to use this control.
- This control is created with modern web technologies and created with efficient logic 
   behind it. 
- Simple to decorate the suggestion list with modern `CSS`.  

- If we have thousands of values in ComboBox, Scrolling and selecting the desired value 
   from ComboBox is time-Consuming. We cant search value in ComboBox. `DropDown` 
   helps us find and search the matching value by allowing the search facility.

- This control is responsive. It's mobile-friendly.
-  When working with ComboBox, we do not have flexibility to separate out 
    suggested(label value) and actual (option) value; whereas WebAtoms `DropDown`
   control allows us to do the same and this makes it more end user-friendly.



</description>
      <pubDate>Monday, March 14, 2022</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/156/dropdown14.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms-DropDown-2t</guid>
    </item>
    <item>
      <title>WebAtoms - Calendar Control</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms--Calendar-Control-2s</link>
      <author>Shubham Khare</author>
      <description>####Introduction

In this article, we will learn about the `AtomCalendar` user-interface control. It displays one month at a time, permits us to select a date, advance from month to month, facilitates the creation of the events.

####What is AtomCalendar?
`WebAtoms AtomCalendar` control is developed on the latest modern web technologies making it fast, lightweight, easy to customize, and easy to execute. This control provides us with all the vital features to assist the users in managing their regular tasks and events with ease.


####Properties of AtomCalendar

- yearStart
- yearEnd
- eventDateClicked

The `yearStart` property takes a number value which sets the limit of the year-selector of AtomCalendar. Years before the value set in `yearStart` will not be available for the selection. 

For example, if the current year is 2022, and the value of `yearStart` = -2, then the `yearStart` will be set to `currentYear` - 2 Years = 2019. Any year preceding the year 2019 will not be available for selection. 


The `yearEnd` property sets the upper limit of the year-selector of `AtomCalendar`. 
For example, if the current year is 2022, and the value of `yearEnd` = 2, then years starting 2025 are filtered from the selector. Any year succeeding the year 2024 will not be available for selection.

The `eventDateClicked` property calls a method when the date on the calendar gets clicked. This property triggers changes in the UI, making the calendar control interactive.

####Code snippet
````javascript
&lt;AtomCalendar 
        yearStart={-2}
        yearEnd= {2}
        eventDateClicked={Bind.event((s, e) =&gt;
                        this.viewModel.dateClicked(e.detail))}&gt;
&lt;/AtomCalendar&gt;
````
#### Is it Customizable?
Yes, `AtomCalendar` control is relatively simple to customize. It provides you with tremendous flexibility to define the presentation of your data. This control has a template feature that gives us the power to style data.

````javascript
&lt;AtomCalendar.itemTemplate&gt;
&lt;div eventClick = {Bind.event((x) =&gt; 
         this.viewModel.dateClicked(x.data))}
         styleBorderRadius = "0px" 
         styleBorder = "1px solid lightgray"
         styleColor = {Bind.oneWay((x) =&gt; x.data.isOtherMonth  ? 
         Colors.gray :  x.data.isWeekend ? 
         Colors.red : Colors.black)}
	  class={Bind.oneWay((x) =&gt; ({ 'date-css': 1,
           'is-other-month': x.data.isOtherMonth,
           'is-today': x.data.isToday,
           'is-weekend': x.data.isWeekend,
           'is-selected': x.localViewModel.selectedDate === x.data,
	    			}))}&gt;
&lt;/AtomCalendar.itemTemplate&gt;
````

In the above code, we defined the `itemTemplate` and showed some inline data of control, which helps us present the data clearly and transform the look and feel of the `AtomCalendar`.


####Benefits of using AtomCalendar

⦁  `AtomCalendar` allows user-defined styles, which makes it customizable according to 
   the theme of a website.

⦁  There is no need to install a separate npm library for using `AtomCalendar`.

⦁  `AtomCalendar` is useful in websites where the content needs to be presented chronologically, for example, events, reminders, memos, meetings, etc.</description>
      <pubDate>Monday, February 28, 2022</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/151/WebAtomsCalendar3.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms--Calendar-Control-2s</guid>
    </item>
    <item>
      <title>WebAtoms - Form</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms--Form-2r</link>
      <author>Ajay Singh</author>
      <description>This article provides you with the first experience of writing the simple basic `Form`. After that, we will show you how to do the simple validation and cover some of writing the `CSS` on this lightweight `Form`.  We will cover all these things with some code snippets.

####What is WebAtoms?

`WebAtoms` is an advanced MVVM framework to write cross-platform applications in HTML5 and Xamarin.Forms.

#### Why do we Need a Form?
A `Form` is the most vital aspect of the user-application interaction for gathering input from the user and storing it in the database.

A Form should contain basic validation to collect valid and accurate data from the user to provide a seamless experience for the user.

####What is WebAtoms Form?

Earlier in the `WebAtoms`, we have defined the `AtomForm` as a class component. To validate the `AtomForm`, we have isolated the logic and validation part to the `ViewModel` section.
We will guide you on how to write the simple `Form` using the `WebAtoms Form` component.

`Form` and `FormField` are javaScript functional components, they are nothing but simple javascript functions.

####How to use the Form?
 ```javascript
 &lt;Form&gt;
     &lt;FormField 
               label="First Name"
               error={Bind.oneWay(() =&gt; 
               validate("first name", this.data.firstName,))}&gt;
        &lt;input 
               value={Bind.twoWaysImmediate(() =&gt;
               this.data.firstName)} /&gt;
     &lt;/FormField&gt;
&lt;/Form&gt;
```
####How to apply multiple validations?

```javascript
const validate = (label: string, value: string, r?: RegExp) =&gt; {
    if (!value)
    {
        return `${label} is required`;
    }
    if (r) {
        if (!r.test(value)) {
            return `${label} is invalid`;
        }
    }
    return "";
};
const validateEmail = (label: string, value: string) =&gt;
validate(label, value, /[a-z0-9\-\.]+\@[a-z0-9\-\.]+[a-z0-9\-]+/i);
```
We have described the `validate` function for input validation. `validateEmail` function
validates the email using the regex.
Below is the simple code snippet which shows the email validation.

```javascript
 &lt;FormField 
      label="Email Address"
      error={Bind.oneWay(() =&gt; validateEmail("Email Address", 
                 this.data.emailAddress))}&gt;
       &lt;input 
            value={Bind.twoWaysImmediate(() =&gt;
            this.data.emailAddress)} /&gt;
  &lt;/FormField&gt;
```
In the above example, we have just displayed a couple of simple validation. In the same manner, one can achieve complicated validation.

####Benefit of WebAtoms Form.

- Form component is very lightweight, meaning it is simple to implement.

- In large applications, there is a requirement of having small UI components like having multiple Forms in a single form, so it becomes easier to implement the validation logic either in ViewModel or in View itself.

 - The error, label, and class attributes of FormField components help us write the neater and cleaner UI with complex validations.

 - You don't need to install any separate NPM library for building the simple form.

- It will improve the speed of writing the code and also reduce the number of lines of code, it becomes easier to maintain the code. 

Check out this [example](https://github.com/web-atoms/web-controls/blob/dev/src/tests/basic/basic-form/BasicForm.tsx).


</description>
      <pubDate>Monday, January 10, 2022</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/145/WebAtomsForm1.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms--Form-2r</guid>
    </item>
    <item>
      <title>YantraJS Performance Improvement using Sequence of T</title>
      <link>https://www.webatoms.in/blog/yantra-js/YantraJS-Performance-Improvement-using-Sequence-of-T-2q</link>
      <author>Akash Kava</author>
      <description>While building parser, we found that we are creating huge list of tokens/nodes to build abstract syntax tree, and from abstract syntax tree we are creating IL code. Each of this list are very huge in size. And while trying to parse script with over 100K lines, parser would take more than 30 seconds.

And while profiling, we found two hot paths taking maximum time.

1. `String.Substring`
2. `Array.Resize`

We removed `String.Substring` by introducing `StringSpan`, this will be covered in a different post.

`Array.Resize`  is called by `List&lt;T&gt;.SetCapacity` method. So we looked up source code of `List&lt;T&gt;`  to investigate further.

## Internals of List&lt;T&gt;

`List&lt;T&gt;` uses an internal array to store items, and when there is no space left in the array, it resizes the array (which basically creates a larger array and copies all items from old array to new array). Default size of the array is 16, and as the list grows, it keeps on doubling the capacity. So when you are adding 17th item on the array, the capacity is set to 32. And when you are adding 33rd item, the capacity is set to 64 and so on with little variance.

This does not hurt performance for small scripts. But when we started parsing larger scripts, it started slowing down exponentially. As an entire script with too many closures and many nested functions, the tree is very large and memory usage and GC pressure is very high.

So we decided to drop `List&lt;T&gt;` and we created `Sequence&lt;T&gt;` which is suitable for append and read once scenario. Most of the times, in parser we are creating a list by appending items but we are only reading them once. However, when array is resized, every node is copied from old array to new array making many enumerations.

## Sequence&lt;T&gt;

`Sequence&lt;T&gt;`  stores nodes of smaller array, and when there is no more free space, it creates a new node with a smaller array. Basically `Sequence&lt;T&gt;` is a linked list of variable sized arrays. Default size is 16, but if you specify an initial capacity, it will create first node of same capacity. `Sequence will not resize any array. The only drawback is indexed access is slower. When a sequence needs to be read, it starts from first node till last and enumerates all array items in the node.

Benefits are,

1. It does not resize existing array
2. It does not increase exponentially
3. Appending is fast
4. Enumerating is marginally slow but not at all noticeable.

Drawbacks,

1. Indexed access is slow
2. Insert is slow

Sequence is a basically a linked list of small arrays. Linked List are not suitable as smaller arrays will be localized while accessing and single node can have multiple array items. When `AddRange` is called with known size, Sequence will allocate all items at once if they are more than capacity.</description>
      <pubDate>Monday, December 20, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/140/List-vs-Sequence.png</image>
      <guid>https://www.webatoms.in/blog/yantra-js/YantraJS-Performance-Improvement-using-Sequence-of-T-2q</guid>
    </item>
    <item>
      <title>Major Version Update 2.0.4</title>
      <link>https://www.webatoms.in/blog/web-atoms-updates/Major-Version-Update-2-0-4-2p</link>
      <author>Akash Kava</author>
      <description>We are happy to announce major version update of Web Atoms for Xamarin Forms with following improvements.

## JSX Initialization Reengineered
Initialization sequence of JSX was little as all property setter were routed through bridge's `SetValue` method, which internally composed full type string of property and performed lookup before actually setting the value.

In this new version, we have added property in prototype of class, so it can be directly set in JavaScript, the conversion will be performed if needed utilizing available TypeConverters.

You can also create new instance of CLR object in JavaScript and set it directly.

This is part of new major update in both JavaScript code and DotNet.

## New Controls

### AtomIconContentView
Many times we need to simply display an icon on left of any content, for this we need to add a new layout unless it is a button. And also now days we are using font icons, so we have made this control to create font icon based content view. 

It has properties, `iconFontSize, iconGlyph, iconColor, secondaryIconGlyph, secondaryIconColor, command, commandParameter`. You can also use duo tone icons.</description>
      <pubDate>Tuesday, December 14, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/138/Version-2.0.4.jpg</image>
      <guid>https://www.webatoms.in/blog/web-atoms-updates/Major-Version-Update-2-0-4-2p</guid>
    </item>
    <item>
      <title>Functional Components along with Controls</title>
      <link>https://www.webatoms.in/blog/tutorials/Functional-Components-along-with-Controls-2n</link>
      <author>Akash Kava</author>
      <description>With new update in WebAtoms, we can now use functional components along with the Controls. Almost all controls are derived from `AtomControl` and `AtomXFControl` for Xamarin Forms. Each of these controls are expensive as they contain heavy logic to perform binding, initialization and disposals. So we have now introduced light weight functional components that basically inlines the JSX nodes inside AtomControl so you can reduce node hierarchy and reuse components easily.

In this tutorial we will display how to use reusable button with font awesome icon and icon + text combination.

## Syntax

Function components are defined as shown below.

### Attributes

We will declare attributes that we can apply, optional attributes can be declared with `?`. Our `FAButton` component will render button with a text if we specify text attribute.

```tsx

export interface IFAButton {
    id?: string;
    icon?: string;
    text?: string;
    eventClick?: any;
    href?: string;
    target?: string;
    title?: string;
    styleDisplay?: string;
    class?: string;
    isVisible?: any;
    subClass?: string;
}
```

### CSS

Lets apply little CSS
```tsx
const css = CSS(
    StyleRule()
    .padding(8)
    .marginLeft(3)
    .marginRight(3)
    .roundBorderFull()
    .display("inline-block")
    .height(40)
    .width(40)
    .defaultBoxShadow()
    .cursor("pointer")
    .backgroundColor(Colors.transparent)
    .hoverBackgroundColor(Colors.lightGreen)
    .and(StyleRule(".pressed")
        .backgroundColor(Colors.lightSteelBlue)
    )
    .child(StyleRule("label.label")
        .display("flex")
        .alignItems("center")
        .child(StyleRule(".fad")
            .fontSize(18)
            .width("100%")
            .color(Colors.purple.withAlphaPercent(0.5))
            .cursor("pointer")
            .and(StyleRule(".red")
                .color(Colors.red)
            )
        )
    )
);
```

### Component

We will now declare the actual component as a function.

```tsx
export default function FAButton({
    id, icon, text, eventClick, href,
    target, title, styleDisplay,
    class: className, subClass
}: IFAButton) {

    const cn = className ?? ( subClass
        ? subClass + " " + css
        : css
    );

    if (href) {
            return &lt;a id={id}
                class={cn}
                target={target}
                title={title}
                styleDisplay={styleDisplay}
                &gt;
                &lt;label class="label"&gt;
                    &lt;i class={icon}/&gt;
                    { text &amp;&amp; &lt;span text={text}/&gt; }
                &lt;/label&gt;
            &lt;/a&gt;;
    }
    return &lt;button id={id} class={cn} eventClick={eventClick}
             title={title} styleDisplay={styleDisplay}&gt;
            &lt;label class="label"&gt;
                &lt;i class={icon}/&gt;
                { text &amp;&amp; &lt;span text={text}/&gt; }
            &lt;/label&gt;
        &lt;/button&gt;;
}

FAButton.className = css;
```

### Usage

Display a link with only an icon...
```jsx
     &lt;FAButton icon="fad fa-play" 
           href="https://www.webatoms.in/play"/&gt;
```

Display a link with only an icon and a text ...
```jsx
     &lt;FAButton text="Play"
              icon="fad fa-play" 
              href="https://www.webatoms.in/play"/&gt;
```

Display a button with a click event
```jsx
     &lt;FAButton text="Play"
              icon="fad fa-play"
              eventClick={clickEventHandler}/&gt;
```

## Advantages

1. Functional components basically acts as a macro and expands JSX nodes inside parent Atom control. 

2. Increases reusability. You can also use binding however, binding can only be applied to the attributes of basic elements.

3. Functional components are expanded in class constructor, you cannot use binding syntax inside functional components.

4. Bindings applied on attributes will be copied as it is to final nodes, they will not cause logic of functional component to be reevaluated.</description>
      <pubDate>Friday, December 3, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/137/Functional-Components.png</image>
      <guid>https://www.webatoms.in/blog/tutorials/Functional-Components-along-with-Controls-2n</guid>
    </item>
    <item>
      <title>WebAtoms - XF.RefreshView</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms--XF-RefreshView-2m</link>
      <author>Ajay Singh</author>
      <description>The `WebAtoms`  `XF.RefreshView` is a container control that lets scrollable content refresh by triggering the pull to refresh. A RefreshView's child must be a scrollable control like ScrollView, CollectionView, or ListView.

#####What are the properties of XF.RefreshView?
- command
- commandParameter
- isRefreshing
- refreshColor

`command` - is executed when a refresh is triggered.

`commandParameter` - Passing the command parameters.

`isRefreshing` -  is a boolean property, which indicates the current state of the control.

`refreshColor` - The color of the progress circle that appears during the refresh.

#####XF.RefreshView Code Sample
```javascript
&lt;XF.RefreshView
    refreshColor={Colors.orange}
    isRefreshing={Bind.twoWays(() =&gt;
                  this.viewModel.isListRefreshing)}
   command={Bind.event(() =&gt;
                     this.viewModel.refresh())}&gt;
       &lt;XF.CollectionView&gt;...&lt;/XF.CollectionView&gt;
&lt;/XF.RefreshView&gt;
```

In this article, we have demonstrated how to use the `XF.RefreshView` control, which refreshes the list or any scrollable content. In this example, we load the movie list using the `XF.CollectionView` and using a few properties of `XF.RefreshView` control; explained at the beginning of the article.

The `command` property is set (as shown in the code snippet) and executed when the user refreshes the content by triggering the pull to refresh.  The refresh method executes every time the user refreshes the content.  

The `refreshColor` property facilitates setting the color of the progress circle that appears when we refresh the movie list.


#####Disabling the XF.RefreshView

There may be instances when it is necessary to disable the pull refresh features of any list or scrollable content. You can disable it by setting `XF.RefreshView` property `isEnabled` to false. 

Click [here](https://test.webatoms.in/play/@web-atoms/sample-cg/13) to download the complete demo.</description>
      <pubDate>Tuesday, November 30, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/136/refreshViewImage.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms--XF-RefreshView-2m</guid>
    </item>
    <item>
      <title>WebAtoms -SwipeView</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms-SwipeView-2c</link>
      <author>Ajay Singh</author>
      <description>#####What is WebAtoms XF.SwipeView?
This control is a container control that contains the items for swipe gestures. 

#####What are the properties of XF.SwipeView?
- LeftItems
- RightItems
- TopItems
- BottomItems

`LeftItems` of type `XF.SwipeItems`, shows the swipe items that are accessible by swiping from the left side of the control.

`RightItems` of type `XF.SwipeItems`, shows the swipe items that are accessible by swiping from the left side of the control.

`TopItems` of type `XF.SwipeItems`, shows the swipe items that are accessible by swiping from the top side of the control.

`BottomItems` of type `XF.SwipeItems`, shows the swipe items that are accessible by swiping from the bottom side of the control.

#####XF.SwipeView Code Sample
The demo code sample explains how to use the control in more detail. We'll start with the left items and right items swipe, which is part of the SwipeView. The hierarchy is straightforward.


```jsx
&lt;XF.SwipeView&gt;
    &lt;XF.SwipeView.LeftItems&gt;
        &lt;XF.SwipeItems&gt;
            &lt;XF.SwipeItem Text="Favorite"
                       BackgroundColor="LightGreen"
                       command={Bind.event(()=&gt; ...)}/&gt;
        &lt;/XF.SwipeItems&gt;
    &lt;/XF.SwipeView.LeftItems&gt;
    &lt;XF.SwipeView.RightItems&gt;
           &lt;-----&gt;
    &lt;/XF.SwipeView.RightItems&gt;
          &lt;--Content--&gt;
&lt;/SwipeView&gt;
```
#####How to Add the custom swipe items? 
We can use the `XF.SwipeItemView` type and design custom swipe items. We created the inbox view using `XF.CollectionView` and used the custom swipe item in this example. The beauty of WebAtoms is that we've incorporated the FontAwesome library, which means we can use any font awesome icons with any of the controls in `WebAtoms`.

Now, in this example, we've demonstrated custom swipe items such as marking an email as a favorite by swiping from the left side and marking as read by swiping from the right side.


```jsx
      &lt;XF.SwipeView&gt;
          &lt;XF.SwipeView.rightItems&gt;
              &lt;XF.SwipeItems&gt;
                   &lt;XF.SwipeItemView
                         backgroundColor={Colors.green}
                         command={Bind.event((x) =&gt; x.data.read = !x.data.read)}&gt;
                                      ---
                   &lt;/XF.SwipeItemView&gt;
            &lt;/XF.SwipeItems&gt;
      &lt;/XF.SwipeView&gt;
```

In the last example, we demonstrated the `XF.SwipeView.RightItems` swipe gesture, and similarly; the left side gesture can be implemented.
The mock data is bound to the `XF.CollectionView` item source.


```jsx
const XFEmailData = [
    {
        emailID:1,
        subject:'WebAtoms Support',
        message:'Login verification code from WebAtoms.',
        image:'',
        favorite: false,
        archived:false,
        dateSent: new Date(),
        isDeleted:false,
        isImportant: false,
        read: false,
    },
    {...},
    {...},
    {...},
]
```
We added functionality to the `ViewModel` component to generate the random color to make our inbox more beautiful. The function `random_rgba` returns a random color that is bound to the view. Binding in `WebAtoms` is simple; check the article of `WebAtoms` on [binding](https://dev.to/web-atoms/different-types-of-bindings-in-web-atoms-for-xamarin-forms-4bf4) for more information.
```jsx
public random_rgba() {
        const letters = '0123456789ABCDEF';
        let color = '#';
        for (let i = 0; i &lt; 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }
```
This [demo](https://www.webatoms.in/play/@web-atoms/sample-a5) can be downloaded.



 
 


</description>
      <pubDate>Thursday, November 11, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/131/gif4.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms-SwipeView-2c</guid>
    </item>
    <item>
      <title>YantraJS now Available in Apache 2.0 License</title>
      <link>https://www.webatoms.in/blog/yantra-js/YantraJS-now-Available-in-Apache-2-0-License-2k</link>
      <author>Akash Kava</author>
      <description>We are happy to announce that new version of YantraJS is now available under `Apache 2.0 License`.

## Why did we change our License?

We want to direct our effort in building larger community to strengthen YantraJS Engine. We are using YantraJS in Web Atoms for Xamarin Forms, which allows us to create .NET User Interface applications in JavaScript. And we want to bring various features of JavaScript to whole .NET User base.

## What will be free?

YantraJS source code released in this repository (contributed by other contributors - merged pull requests) will be available for free under selected license.

### NuGet
| Name                                               | Package                                                                                                                                                        |
|----------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|
| YantraJS (With CSX Module Support)                              | [![NuGet](https://img.shields.io/nuget/v/YantraJS.svg?label=NuGet)](https://www.nuget.org/packages/YantraJS)                           |
| YantraJS.Core (Compiler)| [![NuGet](https://img.shields.io/nuget/v/YantraJS.Core.svg?label=NuGet)](https://www.nuget.org/packages/YantraJS.Core) |
| YantraJS.ExpressionCompiler (IL Compiler)           | [![NuGet](https://img.shields.io/nuget/v/YantraJS.ExpressionCompiler.svg?label=NuGet)](https://www.nuget.org/packages/YantraJS.ExpressionCompiler) |
| WebAtoms.YantraJS                 | [![NuGet](https://img.shields.io/nuget/v/WebAtoms.YantraJS.svg?label=NuGet)](https://www.nuget.org/packages/WebAtoms.YantraJS) |

### Features
1. Compiles JavaScript to .Net Assembly 
2. Strict Mode Only JavaScript*
3. Arrow functions
4. Classes
5. Enhanced object literals
6. Template strings and tagged templates
7. Destructuring
8. `let` `const`
9. Map, Set, WeakMap, WeakSet
10. Symbols
11. Subclassable built-ins
12. Binary and Octal literals
13. Module support
14. Null coalesce
15. Optional property chain `identifier?.[]`, `identifier?.(`, `identifier?.identifier`
16. Rest, Default and Spread Parameters
17. Generators, iterators, for..of
18. Async/Await
19. Optional parameters
20. Many ES5 + ES6 features
21. CommonJS Module Support
21. Easily marshal CLR Object to JavaScript and other way around
23. CSX Module support

`*` Most JavaScript today is available in strict mode, we do not feel any need to support non strict mode as modules are strict by default.

## Sponsorships

We have setup Patreon Page and we will appreciate any help from community.

## Patreon Page
[patreon.com/yantrajs](https://patreon.com/yantrajs)

## Roadmap
The money we will receive via sponsorship will be used to achieve following milestones.

1. Private Fields
2. Async Generators
3. V8 Inspector Protocol
4. Improve Code Generation Speed
5. Increase ECMA conformance
6. Increase test262 success rate
7. Temporal

And many features that will come in future.

### Github Page
[github.com/yantrajs/yantra](https://github.com/yantrajs/yantra)

### Web site
[yantrajs.com](https://yantrajs.com)


</description>
      <pubDate>Sunday, November 7, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/129/YantraJS-Available-under-Apache-2.0-License.gif</image>
      <guid>https://www.webatoms.in/blog/yantra-js/YantraJS-now-Available-in-Apache-2-0-License-2k</guid>
    </item>
    <item>
      <title>Master-Detail View</title>
      <link>https://www.webatoms.in/blog/tutorials/Master-Detail-View-25</link>
      <author>srikanth.naidu</author>
      <description>``WebAtoms`` is an advanced MVVM framework for writing cross-platform applications in HTML5 and Xamarin.Forms.

A master page shows high-level data and a detail page displays low-level data. The user may access comprehensive information about a product by selecting it from a list on the master-detail page.

###Master Page
The master page allows users to swipe through a set of objects in a vertical format. ``CollectionView`` and ``FlexLayout`` are utilized in the master page to retrieve the object from the ``ViewModel``. The content is bound to a vertical list with item attributes listed in columns.


```javascript

&lt;XF.ContentPage title="Master Page"&gt;
    &lt;XF.CollectionView
        itemsSource={Bind.oneWay(() =&gt; this.viewModel.list)}
        itemsLayout="VerticalList"&gt;
        &lt;XF.CollectionView.itemTemplate&gt;
            &lt;XF.FlexLayout&gt;
                        &lt;XF.ImageButton margin="10, 10, 10, 10"
                            command={Bind.event((x) =&gt; {
                            nav.openPage(XFDetailpage, { data: x.data }, { clearHistory: false, frameLess: true }); })}
                            source={Bind.twoWays((x) =&gt; x.data.url)}
                            aspect="AspectFill"
                            heightRequest={150}
                            {...XF.FlexLayout.basis(100)}
                            {...XF.FlexLayout.order(-1)} /&gt;
            &lt;/XF.FlexLayout&gt;
        &lt;/XF.CollectionView.itemTemplate&gt;
    &lt;/XF.CollectionView&gt;
&lt;/XF.ContentPage&gt;
 ```


###ViewModel for the Master Page
We created a ``ViewModel`` containing an array list and connected it to the ``CollectionView`` in a new class. It possesses all of the required properties. We'll link ``ViewModel`` to our user interface.

```javascript
    interface IListModel {
    Id?:string;
    name?: string;
    description?: string;
    price?:string;
    url?:string;
}
 ```

###Binding Data
The ``ItemsSource`` property binds the ``CollectionView`` data source and displays all list items defined in the view and associated properties to particular controls like labels and buttons.
 
###Data Transfer
Using the navigation service, we request the next page and transfer the item there.

```javascript
 &lt;XF.ImageButton
    command={Bind.event((x) =&gt; {
        nav.openPage(XFDetailpage, { data: x.data },
            { clearHistory: false, frameLess: true });
    })}
```
 
###Detail View
This view uses the ``Flexlayout`` to show data in a detail view, allowing visitors to browse through the item's details.

```javascript
         &lt;XF.ContentPage title="Detail Page"&gt;
                &lt;XF.ScrollView&gt;
                    &lt;XF.FlexLayout direction="Column"&gt;
                        &lt;XF.Image margin="10, 10, 10, 10" heightRequest="400"
                            source={Bind.twoWays((x) =&gt; this.viewModel.data.url)}
                            aspect="AspectFill" /&gt;
                        &lt;XF.Label margin="10, 10, 10, 10" text={Bind.twoWays((x) =&gt; this.viewModel.data.name)}
                            fontSize={22} /&gt;
                   &lt;/XF.FlexLayout&gt;
                &lt;/XF.ScrollView&gt;
            &lt;/XF.ContentPage&gt;
```


###Model View for Detail View
We created a ``ViewModel`` in a new class that gets the data from the list page.

```javascript
 export default class DetailpageViewModel extends AtomWindowViewModel {

    public data: any;
}

```

###DemoLink
 
[Demo Link](https://test.webatoms.in/play/@web-atoms/sample-bm/348)
 </description>
      <pubDate>Wednesday, October 27, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/127/WebAtoms.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/Master-Detail-View-25</guid>
    </item>
    <item>
      <title>Yantra Expression Compiler for DotNet</title>
      <link>https://www.webatoms.in/blog/yantra-js/Yantra-Expression-Compiler-for-DotNet-2j</link>
      <author>Akash Kava</author>
      <description>YantraJS is JavaScript built on top of Brand new Expression Compiler which is based on System.Linq.Expressions (referred further as SLE) but with different implementation.

```c#
var a = YExpression.Parameter(typeof(int));
var b = YExpression.Parameter(typeof(int));

var exp = YExpression.Lambda&lt;Func&lt;int,int,int&gt;&gt;("add",
            YExpression.Binary(a, YOperator.Add, b),
            new YParameterExpression[] { a, b });

var fx = exp.Compile();

Assert.AreEqual(1, fx(1, 0));
Assert.AreEqual(3, fx(1, 2));
```

## Methods

There are five different methods to generate and execute the code. They are all available in .NET Standard so they are even available for .NET Core.

### Compile
This method will compile expression to IL in memory, it will not analyze nested lambdas, this is by design to generate IL faster. For nested lambda, please use CompileWithNestedLambdas method. It will return DynamicMethod delegate.

### CompileWithNestedLambdas
When you expression tree contains nested lambda with closures, use this method to generate the IL. It will return DynamicMethod delegate.

### CompileInAssembly
This is similar to CompileToMethod, this method generate an empty assembly and it will return generated method from MethodBuilder. This method will compile nested lambdas correctly.

### CompileToStaticMethod
This is same as CompileToMethod of Linq. This method will compile nested lambdas correctly.

### CompileToInstanceMethod
You can compile lambda with this parameter to an instance method. This method will compile nested lambdas correctly.



## Examples

### Read Array
```c#
var args = YExpression.Parameters(typeof(int[]), typeof(int));

var exp = YExpression.Lambda&lt;Func&lt;int[],int,int&gt;&gt;("load", YExpression.ArrayIndex(
    args[0],
    args[1]
    ), args);

var fx = exp.Compile();

var n = new int[]{1,2,3 };

Assert.AreEqual(1, fx(n, 0));
```

### Nested Closures - Curry
```c#
var a = YExpression.Parameters(typeof(int));

var b = YExpression.Parameters(typeof(int));

var c = YExpression.Parameters(typeof(int));


var lamba = YExpression.Lambda&lt;Func&lt;int, Func&lt;int, Func&lt;int, int&gt;&gt;&gt;&gt;("c",
        YExpression.Lambda&lt;Func&lt;int, Func&lt;int, int&gt;&gt;&gt;("b",
            YExpression.Lambda&lt;Func&lt;int, int&gt;&gt;("inner",
                a[0] + b[0] + c[0],
                c
            ), b
        ),
        a
    );

var fx1 = lamba.CompileInAssembly();

var fx2 = fx1(1);

var fx3 = fx2(2);

var r = fx3(3);

Assert.AreEqual(6, r);
```

### Recursive Fibonacci series
```c#
var a = YExpression.Parameters(typeof(int));

var fibs = YExpression.Parameters(typeof(Func&lt;int,int&gt;));
var fib = fibs[0];

var fibp = YExpression.Parameters(typeof(int));
var p1 = fibp[0];

var f = YExpression.Lambda&lt;Func&lt;Func&lt;int,int&gt;&gt;&gt;("fib_outer", 
    YExpression.Block(
        fibs.AsSequence(),
        YExpression.Assign(fib, YExpression.Lambda&lt;Func&lt;int, int&gt;&gt;("fib",
            YExpression.Block(
                    YExpression.Conditional(
                        p1 &lt;= 1, 
                        YExpression.Constant(0),
                        YExpression.Conditional(
                            YExpression.Equal(p1, YExpression.Constant(2)), 
                            YExpression.Constant(1),
                                YExpression.Invoke(fib, p1 - 1)
                                +
                                YExpression.Invoke(fib, p1 - 2)
                            ))
                )
            ,
            fibp) )
        )
    , a); ;

var outer = f.CompileInAssembly();

var fx = outer();

Assert.AreEqual(3, fx(5));
```

## Expression Visitors
YantraJS Expression Compiler comes with `YExpressionVisitor&lt;T&gt;` and `YExpressionMapVisitor`. `YExpressionVisitor&lt;T&gt;` is very basic, you may never need it unless you are translating expressions to something else. `YExpressionMapVisitor` provides visitor which analyzes entire tree and it will replace child nodes as required. Each node and children will be compared to see if any node is modified and it will modify entire tree. All expressions are immutable.

## Closure Rewriter
SLE generates new types and fields for closures. In YantraJS Expression Compiler we are generating `Box&lt;T&gt;` inside array field of the root class `Closure`. Again we chose this approach to reduce compile time as `AssemblyBuiler` becomes slower for larger code base. We are still working constantly to improve the compilation speed.

## No Validation

API is similar to that of SLE, but implementation is faster as it does not perform any checks whether the expression is correct or not. There are no null checks either. Since we needed to speed up the code generation, we had to skip various checks.

So in order to use the library, you must validate your expressions with SLE and then you can easily replace it with Yantra Expressions.

### Following validations are not performed

1. Label must be within correct block, SLE checks if jumps are possible in blocks. Jumps out of try/catch are not permitted etc.
2. Return/Jump not permitted in finally block.
3. Argument types mismatch, SLE checks each method's input output type with expressions. 

There may be more validations, and we do not plan to add them.

Reason being, we are using this to generate JavaScript IL code, however all these validations are already performed and translated correctly by JavaScript parser and compiler. And there are thousands of unit test of JavaScript which tells us that Expression Compiler is generating code correctly.

## Different Node Types

In SLE, `ConstantExpression` is a single expression holding type `object` of any type. This is a problem while generating code as everything a full list of type check occurs to generate the code. Where else in YantraJS we have classes like `YInt32Constant`, `StringConstant` etc, which can avoid all type checks and generate code faster. For native value types (int etc), there is no boxing for `ConstantExpression` leading to faster execution.

`YArrayIndexExpression`, `YIndexExpression` (for indexed property) and `YPropertyExpression`, `YFieldExpression` are various extra node types which simplifies the code generation.

Assign and Binary expressions are different expressions, again to simplify code generation.

## Sequence of T

We also realized that `List&lt;T&gt;` causes too many re allocations while expression tree is being built, for smaller expressions it does not matter but for extremely large tree, building tree becomes exponentially slower as each node is moved from smaller array to larger array. To solve this issue, we replaced `List&lt;T&gt;` with `Sequence&lt;T&gt;`, which is fast for sequential access and appending items.  In Expressions, most `List&lt;T&gt;` are only built once and only read once. In this case, smaller linked arrays inside `Sequence` reduces GC overhead and memory usage.
</description>
      <pubDate>Tuesday, October 26, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/128/Expression-Compiler.gif</image>
      <guid>https://www.webatoms.in/blog/yantra-js/Yantra-Expression-Compiler-for-DotNet-2j</guid>
    </item>
    <item>
      <title>Version update 1.6.297</title>
      <link>https://www.webatoms.in/blog/web-atoms-updates/Version-update-1-6-297-2h</link>
      <author>Akash Kava</author>
      <description>Following improvements are shipped in this update.

## Improvements

### 1. Calling V8 Method Speed Improvement
We have replaced heap allocation for calling function/methods on JavaScript by using stack allocation.

### 2. Improved OkHttp Calls
We have replaced OkHttpCall with inbuilt async Task, which reduced heap allocation for every single http call.

### 3. Added background for DuoToneFontButton
We have added background Fill color and corner radius to give button kind of look for DuoToneFontButton.

## New Control

### AtomRadioButtonList

We have added new control `AtomRadioButtonList` which is easy to bind and you can track the selected items via binding.

```tsx
&lt;WA.AtomRadioButtonList
    selectedItem={Bind.twoWays(() =&gt;
        this.viewModel.model.emailNotificationSetting, null, {
        fromSource: (v) =&gt; emailNotificationSetting.find((i) =&gt; i.value === v),
        fromTarget: (v) =&gt; v.value
    })}
    itemsSource={emailNotificationSetting}&gt;
    &lt;WA.AtomRadioButtonList.itemTemplate&gt;
    &lt;XF.DataTemplate&gt;
        &lt;XF.Label text={Bind.oneWay((x) =&gt; x.data.label)}/&gt;
    &lt;/XF.DataTemplate&gt;
    &lt;/WA.AtomRadioButtonList.itemTemplate&gt;
&lt;/WA.AtomRadioButtonList&gt;

```

![Atom Radio Button List](/api/attachments/att/125/Screenshot-2021-10-21-142252.jpg)
</description>
      <pubDate>Wednesday, October 20, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/124/Version-1.6.297.jpg</image>
      <guid>https://www.webatoms.in/blog/web-atoms-updates/Version-update-1-6-297-2h</guid>
    </item>
    <item>
      <title>Introducing new JavaScript Engine YantraJS for DotNet</title>
      <link>https://www.webatoms.in/blog/yantra-js/Introducing-new-JavaScript-Engine-YantraJS-for-DotNet-2g</link>
      <author>Akash Kava</author>
      <description>We are happy to announce a brand new Open Source JavaScript engine completely written in C# for .NET.

## Managed JavaScript Runtime
YantraJS is a JavaScript runtime written in .NET Standard. Yantra has two components, Expression Compiler and JavaScript engine.

It is written in .NET standard, so it runs everywhere except iOS which enforces JIT restrictions. However, with help of an interpreter you can still use it on iOS.

## Why did we build it?
We wanted a JavaScript engine with complete support of ES6, including generators and async/await. And we want to officially support as a commercial product. YantraJS is open source and is distributed under Apache 2.0 License.

For more details, please visit [YantraJS Website](https://yantrajs.com)

## Features
1. Compiles JavaScript to .Net Assembly 
2. Strict Mode Only JavaScript*
3. Arrow functions
4. Classes
5. Enhanced object literals
6. Template strings and tagged templates
7. Destructuring
8. `let` `const`
9. Map, Set, WeakMap, WeakSet
10. Symbols
11. Subclassable built-ins
12. Binary and Octal literals
13. Module support
14. Null coalesce
15. Optional property chain `identifier?.[]`, `identifier?.(`, `identifier?.identifier`
16. Rest, Default and Spread Parameters
17. Generators, iterators, for..of
18. Async/Await
19. Optional parameters
20. Many ES5 + ES6 features
21. CommonJS Module Support
21. Easily marshal CLR Object to JavaScript and other way around
23. CSX Module support

`*` Most JavaScript today is available in strict mode, we do not feel any need to support non strict mode as modules are strict by default.

## Roadmap
1. Support for V8 Debugger Protocol
2. Increase ECMAScript conformance
3. Faster IL Serialization
4. Faster Debugging
5. Support for module pollyfills (ability to redirect default node modules, to support dual platform)

## ECMAScript Conformance
Currently we are seeing more than 70% conformance to ECMAScript, reaching 100% is little out of scope as it is very huge and Yantra is only one year old. We are focusing on supporting most used JavaScript patterns instead of targeting 100% compliance due to limited development bandwidth.

## Expression Compiler
YantraJS is built on custom Expression Compiler, which allows us to create expressions similar to that of Linq Expressions. Expression Compiler has several methods to generate IL, you can compile expression to `MethodBuilder`. Since there is no support for Linq to compile expressions to `MethodBuilder`, Yantra Expression Compiler was written from ground up to support saving IL to various ways.

## Engine Types
1. JSContext - plain JavaScript context
2. JSModuleContext - context with modules and clr support
3. YantraJSContext - context with modules, clr and CSX Module support

## How to use?

### Simple Execution
```c#
var context = new JSContext();

// create global function
context["add"] = new JSFunction((in Arguments a) =&gt; {
    return new JSNumber(
         (a[0]?.IntValue ?? 0) + (a[1]?.IntValue ?? 0)
    );
});

var result = context.FastEval("add(4,5)", "script.js");
```

### Wrap CLR Object
Custom CLR types can be wrapped in ClrProxy which will allow you to call any methods directly from JavaScript.

```c#
context["createUri"] = context.CreateFunction((in Arguments a) =&gt; {
    var uri = new Uri(a[0]?.ToString() 
          ?? throw context.NewReferenceError(
                   "At least one parameter expected");
    return new ClrProxy(uri);
}, "add");
var result = context.FastEval(
      "var uri = createUri('https://yantrajs.com'); uri.host");
Console.WriteLine(result);
```

For more information on how to use various types, please visit [YantraJS Examples](https://github.com/yantrajs/yantra/wiki/JavaScript-Engine-Example)

##  Alternative to Razor View in ASP.NET Core
We have created our website using JavaScript as view instead of Razor view, though it started as a simple application, but we realized that by using JavaScript as view, we can easily plugin Server Side Rendering and improve page delivery speed. However, using traditional JSDom is not yet supported due to very heavy dependency on various built in node modules. But you can easily create a wrapper with mocks to render content of your React/Angular components on server easily with YantraJS. Check out source code for our website at [Github Repository for YantraJS Website](https://github.com/yantrajs/web-site)</description>
      <pubDate>Tuesday, October 19, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/123/Copy-of-YantraJS.gif</image>
      <guid>https://www.webatoms.in/blog/yantra-js/Introducing-new-JavaScript-Engine-YantraJS-for-DotNet-2g</guid>
    </item>
    <item>
      <title>Difference between `instanceOf Array` and `Array.isArray`</title>
      <link>https://www.webatoms.in/blog/general/Difference-between-instanceOf-Array-and-Array-isArray-2f</link>
      <author>Akash Kava</author>
      <description>There are two major differences between `instanceOf Array` and `Array.isArray`

## Cross Context Object

In browser, when you access object from different window (such as different iframe from same domain), `instanceOf Array` will return false. However `Array.isArray` will return true.

For example, 
```javascript
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
iArray = window.frames[window.frames.length-1].Array;
var arr = new iArray(1,2,3); // [1,2,3]

// Correctly checking for Array
Array.isArray(arr);  // true
// Considered harmful, because doesn't work through iframes
arr instanceof Array; // false
```

### Why?

Well internally, all root level (global) functions/constructors such as `Array`, `Object` are isolated under the currently executing contexts. Two browser windows or two iframes will have different context and object created in one context will have prototype associated with the context.

When object is accessed in different context, `instanceOf` will fail to identify object's prototype chain in current context.

## Created with `Object.create`

```javascript
var a = Object.create( Array.prototype, {});
a.push(1);
a.push(2);

var b = [];
b.push(1);
b.push(2);
console.log(a.join()); // it will display '1,2'.
console.log(b.join()); // it will display '1,2'.

Array.isArray(a); // false
Array.isArray(b); // true

a instanceOf Array; // true
b instanceOf Array; // true

```

### Why?

With `Object.create`, Array.prototype is present in prototype chain of `a`, so `instanceOf Array` will be true, as in the context of JavaScript, a has prototype of Array. So all the methods of `Array` will work correctly on `a` as those methods are generic.

But `Array.isArray` does not check for prototype, it checks if it was created using `Array` constructor, which internally is a separate type of object in the language it was implemented. Such as in V8, `Array` constructor will create an object of class `V8Array` which inherits `V8Object`. And `Object.create` will create `V8Object`. `Array.isArray` method in V8 will check if the receiver is instance of `V8Array` class in C++. Similarly every JavaScript engine will check natively, what kind of object it is, rather then checking prototype.</description>
      <pubDate>Monday, October 18, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/121/instanceof-Array.jpg</image>
      <guid>https://www.webatoms.in/blog/general/Difference-between-instanceOf-Array-and-Array-isArray-2f</guid>
    </item>
    <item>
      <title>What is CODE to me?</title>
      <link>https://www.webatoms.in/blog/general/What-is-CODE-to-me-2e</link>
      <author>Simmi Kava</author>
      <description>**CREATE**  
&lt;br/&gt;
_Create to inspire, it is all about connecting the missing dots._


**OPTIMIZE**  
&lt;br/&gt;
_Optimize to leverage the learnings; remember knowledge empowers you!._


**DIVERSIFY**  
&lt;br/&gt;
_Dream, diversify- and never miss an angle - Walt Disney._


**EVOLVE** 
&lt;br/&gt;
_Evolve or repeat until you become a better version of yourself._
</description>
      <pubDate>Monday, October 11, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/120/CODE-FullForm.gif</image>
      <guid>https://www.webatoms.in/blog/general/What-is-CODE-to-me-2e</guid>
    </item>
    <item>
      <title>Let's start FRESH!</title>
      <link>https://www.webatoms.in/blog/general/Let-s-start-FRESH-2d</link>
      <author>Simmi Kava</author>
      <description>### It's Time For Positive Change

Mindset and Attitude defines you! 

Learn from your failures and embrace your imperfections. 
The "**new you**" version can only be released
if you step out of your comfort zone and welcome the change. 

Thanks!
Have a nice weekend. 

</description>
      <pubDate>Thursday, October 7, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/119/linkedin.gif</image>
      <guid>https://www.webatoms.in/blog/general/Let-s-start-FRESH-2d</guid>
    </item>
    <item>
      <title>Version Update 1.6.269</title>
      <link>https://www.webatoms.in/blog/web-atoms-updates/Version-Update-1-6-269-2b</link>
      <author>Akash Kava</author>
      <description>This version update includes following changes.

## Improvements
1. Performance of AtomChoiceView's scroll to selection improved
2. Constructor Parameter matching improved, with this you can now initialize `XF.FontImageSource` inline as shown below.

```tsx

   &lt;XF.ImageButton
          source={Object.assign(new XF.FontImageSource(), {
                fontFamily: FontAwesomeSolid,
                glyph: FontAwesomeSolid.circle
                color: XF.Color.orangeRed
          })}
          /&gt;

```

## New Control

We have added new `AtomDuoToneFontImageButton` control, 
![image](/api/attachments/att/114/Due-Tone-Icons.JPG)

```tsx
     &lt;WA.AtomDuoToneFontImageButton
               source={Object.assign(
                new WA.AtomDuoToneFontImageSource(), {
                   fontFamily: FontAwesomeSolid,
                   glyph: FontAwesomeSolid.circle
                   color: XF.Color.orangeRed
                   secondaryOpacity: 0.5
               })}
              /&gt;
```</description>
      <pubDate>Sunday, October 3, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/113/Version-1.6.269.jpg</image>
      <guid>https://www.webatoms.in/blog/web-atoms-updates/Version-Update-1-6-269-2b</guid>
    </item>
    <item>
      <title>WebAtoms: AtomExpander - Expandable Container to host content</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms-AtomExpander--Expandable-Container-to-host-content-2a</link>
      <author>Simmi Kava</author>
      <description>### WebAtoms: AtomExpander - User Interface Control   
&lt;br/&gt;

**What is AtomExpander?**

This control is an expandable container to host any content. It contains a header and expandable content part which allows content toggling by clicking on the header. 


**What are the properites of AtomExpander?**

- AtomExpander.detail
- AtomExpander.detailTemplate
- AtomExpander.icon 

**What is the difference between "AtomExpander.detail" and "AtomExpander.detailTemplate"?**

In `AtomExpander.detail` the element already exists during the runtime whereas in `AtomExpander.detailTemplate` the element is created when the header text is clicked. 


**What is the purpose of AtomExpander.icon?**

This is a bindable property which can be used to add an icon to the header text. For e.g. you can integrate it with FontAwesome icons. 

WebAtoms now provides AtomExpander as the control for Xamarin.Forms. Let us learn the how to use the control through an example.

**AtomExpander Code Sample**

The demo example displays various controls `WebAtoms` offers and explains how to use the `AtomExpander` control and its important properties. In this example we are explaining what controls does WebAtoms offer and one liner description of each of the controls.  The sample also explain how to integrate the `Font Awesome` icon with the header (or the expandable) text. 

Let's learn how to design the content page / layout for AtomExpander.

**Content Page Design**

```tsx

&lt;WA.AtomExpander 
    padding={5}
    backgroundColor={XF.Color.white}
    horizontalOptions="FillAndExpand"
    &gt;
    &lt;WA.AtomExpander.icon&gt;
        &lt;XF.FontImageSource
            fontFamily={FontAwesomeSolid}
            glyph={FontAwesomeSolid.tags}
            color={XF.Color.orangeRed}
        /&gt;
    &lt;/WA.AtomExpander.icon&gt;
    &lt;XF.Label
    fontSize="20"
    text="AtomChips"
    /&gt;  
    &lt;WA.AtomExpander.detail&gt;
        &lt;XF.Label
            text="This control is a material design dynamic element 
            which can be used as input, or to select and filter 
            content or to trigger an action."
        /&gt;       
    &lt;/WA.AtomExpander.detail&gt;
&lt;/WA.AtomExpander&gt;
``` 

For the complete sample, you may refer the demo link. 

We do not need a ViewModel for this example. But we might need a ViewModel for some other requirement. For e.g. after the control is expanded you want to show certain items and when the control is collapsed you want to hide certain set of items. 

**XF-Controls version being used is 2.0.47.**  

[Demo Link](https://www.webatoms.in/play/@web-atoms/atom-expander-sample)






</description>
      <pubDate>Wednesday, September 29, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/112/Linkedin-AtomExpander.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms-AtomExpander--Expandable-Container-to-host-content-2a</guid>
    </item>
    <item>
      <title>WebAtoms: WA.AtomCheckBoxList Control</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms-WA-AtomCheckBoxList-Control-28</link>
      <author>Ajay Singh</author>
      <description>Before proceeding to the `WA.AtomCheckBoxtList` user interface control, let's first understand the simple `XF.CheckBox` control. 

In `WebAtoms`, to change the state of the `checkBox`, we need to use the `isChecked` property and we need to bind it to the control. Single `checkBox` is primarily used for a terms of service agreements, remember me in login pages, or in YES or NO scenario.
`XF.CheckBox` demo is available from this [link.](https://github.com/web-atoms/xf-samples/blob/master/src/samples/check-box/CheckBoxView.tsx)

####Create a simple WA.AtomCheckBoxtList.
This selection control allows users to select one or more options from a group of preset choices. `WebAtoms` facilitates selection of one or more options from the set through the user interface control named `WA.AtomCheckBoxList`.

Let us first design the layout.

```javascript
export default class MainPage extends AtomXFContentPage {

    @BindableProperty
    public ethnicities: any[];


    public viewModel: MainPageViewModel;

    public create() {

        this.ethnicities= [];


        this.viewModel = this.resolve(MainPageViewModel);
        this.render(
            &lt;XF.ContentPage title="AtomCheckBoxList Sample"&gt;
                &lt;XF.Frame padding="0"
                    backgroundColor={Colors.white}
                    borderColor={Colors.lightGray} &gt;
                    &lt;XF.StackLayout orientation="Vertical" isClippedToBounds="true"&gt;
                        &lt;XF.Label text="How would you describe your ethnic origin?"
                            fontSize={22}
                            padding="20,10,0,20"
                            textColor={Colors.black} /&gt;
                        &lt;WA.AtomCheckBoxList
                            padding="10"
                            itemsSource={ethiics}
                            selectedItems={Bind.oneWay(() =&gt; this.ethnicities)} &gt;
                            &lt;WA.AtomCheckBoxList.itemTemplate&gt;
                                &lt;XF.DataTemplate&gt;
                                    &lt;XF.Label
                                        verticalOptions="Center"
                                        verticalTextAlignment="Center"
                                        fontSize={20}
                                        fontAttributes="Bold"
                                        textColor={Colors.black}
                                        text={Bind.oneWay((x) =&gt; x.data)} /&gt;
                                &lt;/XF.DataTemplate&gt;
                            &lt;/WA.AtomCheckBoxList.itemTemplate&gt;
                        &lt;/WA.AtomCheckBoxList&gt;
                        &lt;XF.Label
                            fontSize={18}
                            padding="20,10,0,20"
                            text={Bind.oneWay(() =&gt; this.ethnicities.length
                                ? this.ethnicities.join(" | ")
                                : "...")}/&gt;
                    &lt;/XF.StackLayout&gt;
                &lt;/XF.Frame&gt;
            &lt;/XF.ContentPage&gt;);
    }

}
```

The beauty of this control is the customization; one can customize the entire template using `DataTemplate`.
&lt;br/&gt;
&lt;br/&gt;
Now let us understand the property which we have used: &lt;br/&gt;&lt;br/&gt;
`itemsSoruce` &lt;br/&gt;
`selectedItems` &lt;br/&gt;

To bind the collection of choices we have to use the `itemsSource` property and that collection of data comes from the mock data.
&lt;br/&gt;
&lt;br/&gt;
To collect or show the user selected choices (may be single or multiple ) we have to bind the `selectedItems` property to this control.


#### Mock data looks like this.
```javascript
 const ethiics = [
    "Caucasian",
    "African American",
    "Indian",
    "Asian",
    "Ethnically Ambiguous",
    "Eurasian",
    "European",
    "Hispanic",
    "Semitic",
    "Slavic"
];
```
This demo can be downloaded from this [link.](https://www.webatoms.in/play/@web-atoms/sample-9g)
</description>
      <pubDate>Monday, September 27, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/110/AtomChecks.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms-WA-AtomCheckBoxList-Control-28</guid>
    </item>
    <item>
      <title>SQL Index Not Utilized on Conditional Filter and DatePart</title>
      <link>https://www.webatoms.in/blog/developer-guide/SQL-Index-Not-Utilized-on-Conditional-Filter-and-DatePart-29</link>
      <author>Akash Kava</author>
      <description>Ever wondered why sql will not use the index and still perform very slow. Here are few points where the queries will ignore index.

## CONDITIONAL FILTER

Consider following stored procedure

```sql
CREATE STORED PROCEDURE [UpdateAllItems]
     @days int = 0
BEGIN
     declare @date date;
     set @date = DATEADD(day, @day,  GETUTCDATE());
     UPDATE Projects 
     SET
          ...
          ...
     WHERE
          @days = 0 OR DateUpdated &gt; @date
END
```

The above query looks like we want to either update all projects or only the projects which were modified in before given days. So we expect this query to run very long if `@days is 0`, but we expect it to run fast when `@days is 1`. Unfortunately, query engine will not use index when `@days is `.

Because query engine will use index only if query references column without `OR`, Irrespective of which path it will take at runtime. Query analyzer cannot change query based on the input parameters.

So above query should be rewritten as following.
```sql
CREATE STORED PROCEDURE [UpdateAllItems]
     @days int = 0
BEGIN
     declare @date date;
     set @date = DATEADD(day, @day,  GETUTCDATE());
     IF @days = 0 
        UPDATE Projects 
        SET
             ...
             ...;
     ELSE
        UPDATE Projects 
        SET
             ...
             ...;
        WHERE DateUpdated &gt; @date    
END
```

In above example, server knows that it needs to use index in the ELSE path.

## DATEPART FILTER

I have seen many people write following query to compute something for given year, for example lets say we want count of all `projects` updated in given year and we have index of `DateUdated` on the Projects table.

```sql
SELECT count(*) from Projects WHERE DATEPART(YEAR, DateUpdated) = 2020;
```
Above query will cause `INDEX SCAN` which is slower than `INDEX SEEK`.  To speed up above query, we can write following query.
```sql
SELECT count(*) from Projects WHERE DateUpdated &gt; '2020-01-01' AND DateUpdated &lt; '2021-01-01';
```
Above query will do INDEX SEEK and will perform faster than the previous one. If tables are very small, the difference will not be visible, but when we have millions of rows, the SCAN will be much slower than the SEEK.



</description>
      <pubDate>Sunday, September 26, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/109/SQL-QUERY-INDEXES-IGNORED.jpg</image>
      <guid>https://www.webatoms.in/blog/developer-guide/SQL-Index-Not-Utilized-on-Conditional-Filter-and-DatePart-29</guid>
    </item>
    <item>
      <title>Version update 1.6.262</title>
      <link>https://www.webatoms.in/blog/web-atoms-updates/Version-update-1-6-262-27</link>
      <author>Akash Kava</author>
      <description>New version 1.6.262 contains following fixes

## Improvements

1. `HorizontalLayout` attached property added in `AtomPopup`, in which you can align popup to left of right aligned content.
2. `HeaderBackground` and `DetailBackground` brush properties are added in `AtomExpander`.
3. Fixed iOS bug which did not display Header of `AtomExpander`

## AtomCheckBoxList control

We have added new control, `AtomCheckBoxList`, which makes it easy to display set of check boxes for given items from items source. And selected items are updated in `SelectedItems` property.

![image](/api/attachments/att/108/CheckBoxList.png)
</description>
      <pubDate>Wednesday, September 22, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/106/Version-1.6.262.jpg</image>
      <guid>https://www.webatoms.in/blog/web-atoms-updates/Version-update-1-6-262-27</guid>
    </item>
    <item>
      <title>Product Quality is your responsibility!</title>
      <link>https://www.webatoms.in/blog/general/Product-Quality-is-your-responsibility-26</link>
      <author>Simmi Kava</author>
      <description>Deliver quality product, make it your habit!

Seamless functioning of your end product is essential for any business. Maintaining product (code) quality is not an easy task. Meeting deadlines should not hamper the quality of code. 

Consistency has positive impact on the product quality and one must take efforts to maintain it. Follow the laid guidelines across the application or product development cycle. </description>
      <pubDate>Tuesday, September 21, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/105/Quality-Quotes.png</image>
      <guid>https://www.webatoms.in/blog/general/Product-Quality-is-your-responsibility-26</guid>
    </item>
    <item>
      <title>Version update 1.6.249</title>
      <link>https://www.webatoms.in/blog/web-atoms-updates/Version-update-1-6-249-24</link>
      <author>Akash Kava</author>
      <description>In this version update we have made following improvements.

## Improvements

1. Weak Reference removed from iOS, we had initially added Weak Reference of Xamarin Control in iOS UI Graph to avoid memory leaks, however since we have improved dispose pattern for controls and bindings, we no longer need to pass weak reference.

2. We have set RecycleElement recycling strategy for ListView displayed in Popups for AtomChips and new control AtomSuggestions.

3. Popups are automatically scrolled to top by bringing the target UI to top if it is inside a scroll view. You can turn it off by setting `AtomPopup.SetScrollUp(target, false)`.

## New Control

### AtomSuggestions

We have added new control, `AtomSuggestions` which will display list of items horizontally  till it fills up all the space and then it will display "More" link, which will then open a popup list view to select items from. There is `ItemTappedCommand` which will be executed when you click any of items displayed.</description>
      <pubDate>Sunday, September 19, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/98/Version-1.6.249.png</image>
      <guid>https://www.webatoms.in/blog/web-atoms-updates/Version-update-1-6-249-24</guid>
    </item>
    <item>
      <title>Getting Started with WebAtoms XF.CarouselView</title>
      <link>https://www.webatoms.in/blog/tutorials/Getting-Started-with-WebAtoms-XF-CarouselView-22</link>
      <author>Ajay Singh</author>
      <description>In this blog, I am going to implement a Gallery of photos with a title and description using `WebAtoms XF.CarouselView`.

####CarouselView 
The carousel view is a view for presenting data in a scrollable layout, where users can swipe to move through a collection of items. By default, `XF.CarouselView` displays its item horizontally.

####Creating a Data Model for  XF.CarouselView.
Create a simple data source as shown in the following code example in a new class file. It has the all the properties which we are going to bind to our `XF.CarouselView` user interface control.

```javascript
export default interface IFlowerModel {
    name?: string;
    image_link?:string;
    description?:string;
}
```

####Creating a simple ViewModel.
This sections explains how to load the data source using mock data.

```javascript
import { AtomViewModel } from "@web-atoms/core/dist/view-model/AtomViewModel";
import Load from "@web-atoms/core/dist/view-model/Load";
import IFlowerModel from "./IFlowerModel";

export default class XFCarouselViewModel extends AtomViewModel {
    public flowers: IFlowerModel[] = [];

    public flowerList: IFlowerModel[] = [
        {
            name: "White &amp; Yellow Daisy",
            image_link:"https://images.unsplash.com/photo-1526495107727-0c4a173230c3?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;ixlib=rb-1.2.1&amp;auto=format&amp;fit=crop&amp;w=634&amp;q=80",
            description:"Bellis perennis, the daisy, is a common European species of the family Asteraceae, often considered the archetypal species of that name."
        },
        {
            name: "Blue Rose",
            image_link:"https://images.unsplash.com/photo-1564640227760-db286729bf83?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;ixlib=rb-1.2.1&amp;auto=format&amp;fit=crop&amp;w=564&amp;q=80",
            description:"A blue rose is a flower of the genus Rosa (family Rosaceae) that presents blue-to-violet pigmentation instead of the more common red, white, or yellow."
        },
        {
            name: "White Rose",
            image_link:"https://images.unsplash.com/photo-1523996381875-89483b0c2eca?ixlib=rb-1.2.1&amp;ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;auto=format&amp;fit=crop&amp;w=564&amp;q=80",
            description:"The White Rose (German: Weiße Rose, pronounced [ˈvaɪ̯sə ˈʁoːzə] (About this soundlisten)) was a non-violent, intellectual resistance group in Nazi Germany."
        },
        {
            name: "Purple Orchid ",
            image_link:"https://images.unsplash.com/photo-1534885320675-b08aa131cc5e?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;ixlib=rb-1.2.1&amp;auto=format&amp;fit=crop&amp;w=675&amp;q=80",
            description:"Orchis mascula, the early-purple orchid,[1] early spring orchis, is a species of flowering plant in the orchid family, Orchidaceae."
        },
        {
            name: "Red Rose",
            image_link:"https://images.unsplash.com/photo-1496062031456-07b8f162a322?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&amp;ixlib=rb-1.2.1&amp;auto=format&amp;fit=crop&amp;w=701&amp;q=80",
            description:"A rose is a woody perennial flowering plant of the genus Rosa, in the family Rosaceae, or the flower it bears."
        },
    ]
    public selectedItem: IFlowerModel;

    @Load({init: true})
    public async loadFlowers() {
        this.selectedItem = this.flowerList[0];
        this.flowers.replace(this.flowerList);
    }
}
```

In the above `ViewModel`, we have loaded the data source in `loadFlowers` method.If `init` is true, method will be executed when `ViewModel` is initialized.

####Binding data to the XF.CarouselView.
To bind the data source of the `XF.CarouselView`, set the `itemsSource` property and to show the current item, bind the `CurrentItem` of `XFCarouselView` with the selectedItem property which defines in the `ViewModel`. 

```javascript
export default class XFCarouselView extends AtomXFContentPage {

    public viewModel: XFCarouselViewModel;
    public create() {
        this.viewModel = this.resolve(XFCarouselViewModel);

        this.render(&lt;XF.ContentPage title="Home" &gt;
            &lt;XF.StackLayout padding="20" backgroundColor={Colors.white}&gt;
                &lt;XF.CarouselView
                    currentItem = {Bind.oneWay(()=&gt; this.viewModel.selectedItem)}
                    itemsSource={Bind.oneWay(()=&gt; this.viewModel.flowers)}&gt;
                        &lt;XF.CarouselView.itemTemplate&gt;
                            &lt;XF.DataTemplate&gt;
                                &lt;XF.StackLayout&gt;
                                    &lt;XF.Frame
                                        hasShadow="true"
                                        borderColor={Colors.darkGray}
                                        cornerRadius={5}
                                        margin={10}
                                        heightRequest={300}
                                        horizontalOptions="Center"
                                        verticalOptions="CenterAndExpand"&gt;
                                            &lt;XF.StackLayout&gt;
                                                &lt;XF.Label
                                                    text= {Bind.oneWay((x)=&gt; x.data.name)}
                                                    fontAttributes="Bold"
                                                    fontSize={20}
                                                    padding="5"
                                                    textColor={Colors.black}
                                                    horizontalOptions="Center"
                                                    verticalOptions="Center"/&gt;
                                                &lt;XF.Image
                                                    aspect="AspectFill"
                                                    source={Bind.oneWay((x) =&gt; x.data.image_link + "/150.jpg")}
                                                    heightRequest={150}
                                                    widthRequest={200}
                                                    horizontalOptions="Center" /&gt;
                                                &lt;XF.Label
                                                    text= {Bind.oneWay((x)=&gt; x.data.description)}
                                                    fontSize={14}
                                                    margin="10"
                                                    padding="10"
                                                    fontAttributes="Bold"
                                                    textColor={Colors.black}/&gt;
                                            &lt;/XF.StackLayout&gt;
                                    &lt;/XF.Frame&gt;
                                &lt;/XF.StackLayout&gt;
                            &lt;/XF.DataTemplate&gt;
                        &lt;/XF.CarouselView.itemTemplate&gt;
                &lt;/XF.CarouselView&gt;
            &lt;/XF.StackLayout&gt;
        &lt;/XF.ContentPage&gt;)
    }
}
```
####Properties
`CurrentItem` When the currently displayed item changes, the CurrentItem property will be set to the value of the item. 
`ItemsSource`, of type IEnumerable, specifies the collection of items to be displayed, and has a default value of null.

###See Also
[WebAtoms Xamarin Forms Fiddle](https://dev.to/web-atoms/introducing-xamarin-forms-fiddle-2h1i).
&lt;br/&gt;
[Full code example](https://www.webatoms.in/play/@web-atoms/sample-8x/1).

</description>
      <pubDate>Thursday, September 16, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/96/WebAtomsC.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/Getting-Started-with-WebAtoms-XF-CarouselView-22</guid>
    </item>
    <item>
      <title>WebAtoms: AtomChips Control</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms-AtomChips-Control-21</link>
      <author>Simmi Kava</author>
      <description>##What are Chips?  
&lt;br/&gt;
Chips are material design dynamic elements which can be used as input, or to select and filter content or to trigger an action. 

Buttons are consistent in appearance and triggers expected or familiar action where as chips are dynamic compact elements percevied as interactive environment element. 

You can learn more about chips on [material.io](https://material.io/components/chips#types).

WebAtoms now provides `AtomChips` as the control for Xamarin.Forms. Let us learn the how to use the control through an example. 

### Practical Use
Hashtags (# tags) are common metadata tag that enables indexing, grouping, sharing and referencing the content. So if we have a particular blog or article and we want to specify what information does the article convey, we can use **#tags**. Let us learn how AtomChips can be used to input hashtags for a given article. 

###AtomChips Code Sample  

Let us first design the layout.
```TypeScript
import Bind from "@web-atoms/core/dist/core/Bind";
import XNode from "@web-atoms/core/dist/core/XNode";
import Pack from "@web-atoms/core/dist/Pack";
import WA from "@web-atoms/xf-controls/dist/clr/WA";
import XF from "@web-atoms/xf-controls/dist/clr/XF";
import AtomXFContentPage from "@web-atoms/xf-controls/dist/pages/AtomXFContentPage";
import MainPageViewModel from "./MainPageViewModel";

// @web-atoms/xf-samples is name of current package
// to import an image, enter full node style module path
import logo from "@web-atoms/xf-samples/src/images/web-atoms.png";

// @web-atoms-embed: navigation-page

@Pack
export default class MainPage extends AtomXFContentPage {

    public viewModel: MainPageViewModel;

    public create() {

        this.viewModel = this.resolve(MainPageViewModel);

        this.render(&lt;XF.ContentPage&gt;
        &lt;XF.Grid&gt;
            &lt;XF.ScrollView&gt;
                &lt;WA.AtomForm&gt;
                    &lt;XF.Label
                    padding={10}
                    text="Web Atoms is an advanced MVVM framework to write cross platform applications in HTML5 and Xamarin.Forms.Web Atoms allows you to create Xamarin Forms app in JSX/JavaScript along with C#. Web Atoms allows use of both NPM and NuGet. Hosting JSX/JavaScript on web server allows you to quickly update the apps quickly with Code Push and it also allows you to distribute side by side versions of the same app. Using JavaScript modules, you can divide large app into smaller modules, also offer localization using modules with reduced app size."/&gt;
                
                    &lt;WA.AtomChips
                        padding={10}
                        entryMode="Search"
                        search={Bind.twoWays(() =&gt; this.viewModel.search)}
                        itemsSource={Bind.oneWay(() =&gt; this.viewModel.tags)}
                        selectedItems={Bind.oneWay(() =&gt; this.viewModel.enteredTags)}&gt;
                        &lt;WA.AtomChips.itemTemplate&gt;
                            &lt;XF.DataTemplate&gt;
                                &lt;XF.Label
                                    text={Bind.oneWay((x) =&gt; x.data.label )}
                                /&gt;
                            &lt;/XF.DataTemplate&gt;
                        &lt;/WA.AtomChips.itemTemplate&gt;              
                    &lt;/WA.AtomChips&gt;

                    &lt;XF.BoxView heightRequest={200}/&gt;
                
                &lt;/WA.AtomForm&gt;
               &lt;/XF.ScrollView&gt;
        &lt;/XF.Grid&gt;
        &lt;/XF.ContentPage&gt;);
    }

}

```


Now, let us understand the layout. AtomChips needs
1. entryMode
2. search text (if applicable)
3. itemsSource
4. selectedItems

Each of the parameter is explained in the image below. 

![image](/api/attachments/att/88/snipedgesremoved.png)


Now let us write the logic

```TypeScript
import { AtomViewModel } from "@web-atoms/core/dist/view-model/AtomViewModel";
import Load from "@web-atoms/core/dist/view-model/Load";
import tags from "./tags";

export default class MainPageViewModel extends AtomViewModel {

    public list = [];
    public tags = null;
    public enteredTags = [];
    public search: string;

    @Load({init: true, watch: true})
    public loadStart() {
        const s = this.search;
        if (s) {
            this.tags = tags.filter((c) =&gt; c.label.toLowerCase().indexOf(s.toLowerCase()) !== -1);
        }else {
            this.tags = null;
        }
    }

}

```
The text user enters is converted to lowercase and matched with the text in our itemsSource array.

Let us look how the **`itemsSource`** (tags.ts) will look like.

```TypeScript
const tags = [
{
    label: "Choose a tag",
    value: "SELECT"
},
{
    label: "TypeScript",
    value: "TypeScript"
},
{
    label: "JavaScript",
    value: "JavaScript"
},
{
    label: "Xamarin.Forms",
    value: "Xamarin.Forms"
},
...
];
export default tags;

```

### Demo Link
[AtomChips Sample](https://www.webatoms.in/play/atom-chips-tags-sample)

**PS:** There is known bug in Xamarin.Forms because of which in `Android` the rectangle that is shown behind the AtomChips searched text is not correctly visible. The sample works perfectly fine in `ios`. </description>
      <pubDate>Wednesday, September 15, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/87/Web-Atoms-Chips-Sample-withoutimage.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms-AtomChips-Control-21</guid>
    </item>
    <item>
      <title>Minor Version 1.6.246 Update</title>
      <link>https://www.webatoms.in/blog/web-atoms-updates/Minor-Version-1-6-246-Update-20</link>
      <author>Akash Kava</author>
      <description>We are happy to announce following new features in this release Version 1.6.245.

## Method Overloads Added

Method overloads for `InvokeFunction`, `CreateNewInstance` and `InvokeMethod` in `IJSValue` are added to reduce array allocation. There is no change in exiting APIs, they will continue to work as it is. C# compiler will automatically choose the method with same parameters instead of creating an array. However, internal implementation will allocate an array for parameter, but we have managed to reduce the array allocation by 50%.

## New Type JSDelegate

We have added new Type `JSDelegate` which creates a typed delegate for JavaScript function. So you can easily assign JavaScript function as delegates. Example explained in next section. 

## TextToModel Delegate in AtomChips

We have added `TextToModel` property of type `Func&lt;string, object&gt;` which will be used by the control to convert entered text into any object model. If it is null, entered text will be added to `SelectedItems` array.

```typescript
   &lt;WA.AtomChips
           selectedItems={Bind.oneWay(() =&gt; this.viewModel.selectedItems)}
           textToModel={(text) =&gt; ({ label: text, value: 0 })}&gt;
           ...
```

In example above, entered text will be set as label, and object literal will be added to `selectedItems`. 

## New Control - AtomExpander

We have added new `AtomExpander` control, which has following properties.

1. **IsExpanded** - This is controlled by the drop down arrow, however, you can also bind it and update it from the code. If it is true, the details will be visible.
2. **Icon** - ImageSource of an Image that will be be displayed on the left corner.
3. **Detail** - You can set any `View` as child of `Detail` property, it will be hidden and it will be visible only when `IsExpanded` is set true.
4. **DetailTemplate** - Instead setting detail, you can set this property as `XF.DataTemplate` and a new detail will only be created if control is in expanded state. As soon as control is collapsed, detail View will be destroyed.

## New Control - AtomChoiceView

We have added new `AtomChoiceView` control, which is same as `AtomXFComboBox` but it is written in C#. It has following properties.

1. **ItemsSource** - list of items to be displayed in popup, choices will be displayed even if it is empty.
2. **SearchEnabled** - a text editor will be displayed as soon as the control is tapped, you can use `Search` property to filter your items source.
3. **DropDownHeight** - height of the popup, default is 200
4. Prompt - a selection message displayed if `SelectedItem` is null
5. **EmptyItemTemplate** - Prompt that will be displayed if `SelectedItem` is null , `Prompt` will be ignored and this template will be displayed as Prompt.
6.  **ItemTemplate** - item template for the choices and selected item.
7. **SelectionStartCommand** - it will be executed when the choice popup was opened.
8. **SelectionEndCommand** - it will be executed when the choice popup was cancelled or closed.
9. **Search** - the text that is entered in search box if `SearchEnabled` was set to true, you can use this to filter your items source.



</description>
      <pubDate>Sunday, September 12, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/86/Version-1.6.246.jpg</image>
      <guid>https://www.webatoms.in/blog/web-atoms-updates/Minor-Version-1-6-246-Update-20</guid>
    </item>
    <item>
      <title>Getting started with WebAtoms XFListView.</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms-XFLIstView-Control-1Z</link>
      <author>Ajay Singh</author>
      <description>This section provides a quick overview of WebAtoms XFListView user interface control for Xamarin Forms.

### Create a Simple XFListView
This section explains how to create a XFListView in WebAtoms Xamarin Forms. In this particular example we will show the real-time crypto data from free public APIs."
Since the API gets many hits in a day, we are replacing it with mock data.

### Creating a Data Model for XFListView.
 Create a simple data source as shown in the following code example in a new class file. It has the all the properties which we are going to bind to our `XFListView` user interface control.
```javascript
export default class ICoinWatchModel {
    symbol?: string;
    priceUsd?: string;
    changePercent24Hr?: string;
};
```
###Creating a simple ViewModel.
This sections explains how to load the data source using mock data.
```javascript
  export default class XFCoinWatchViewModel extends AtomViewModel {

    public coinList: ICoinWatchModel[] = [];

    public option = {
        style: 'percent',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
     };
     public percentageFormatter = new Intl.NumberFormat("en-US", this.option);
 
     public coins:ICoinWatchModel[] = [
       {
            symbol: "BTC",
            priceUsd: "46115.0480271388304650",
            changePercent24Hr: "-0.5095168590745112",
        },
        {
            symbol: "ETH",
            priceUsd: "3387.2839227538603109",
            changePercent24Hr: "-3.8610020887697443",
        },
        {
            symbol: "ADA",
            priceUsd: "2.4690387416910484",
            changePercent24Hr: "-5.1234648122416866"
        },
        {
            symbol: "BNB",
            priceUsd: "413.6486527570754022",
            changePercent24Hr: "-1.2227312211470998"
        },
        {
            symbol: "USDT",
            priceUsd: "1.0005463306761874",
            changePercent24Hr: "0.0139636869853852"

        },
        {
            symbol: "SOL",
            priceUsd: "182.0717581022814142",
            changePercent24Hr: "-14.0451497633219732"
        },
        {
            symbol: "XRP",
            priceUsd: "1.0861040549891727",
            changePercent24Hr: "-3.8228157386158285"
        }
     ]
    @Load({init: true})
    public async loadCoins() {
      this.coinList.replace(this.coins);
    }

   public formatPercentage(value:number) {
       return this.percentageFormatter.format(value);
   }

    public format(value: number) {
        return new Intl.NumberFormat("en-US",
             {
                style: 'currency',
                currency: 'USD',
                minimumIntegerDigits:2
             }).format(value);
    }

}
```
In the above `ViewModel`, we have loaded the data source in `loadCoins` method.If `init` is true, method will be executed when `ViewModel` is initialized.The difference in the current market value is shown as percentage; column named 'Change', the currency under Price column is formatted using [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat).

###Binding data to the XFListView.
To bind the data source of the XFListView, set the `itemsSource` property as shown as follows,The following code example binds the collection created in the `ViewModel`. Using the one way bindings and [Math.sign](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign) function of JavaScript to check the number is positive or negative.
```javascript
export default class XFCoinWatch extends AtomXFContentPage {

    public viewModel: XFCoinWatchViewModel;

    public create() {
        this.viewModel = this.resolve(XFCoinWatchViewModel);
        this.render(&lt;XF.ContentPage 
                               title="Coin Watch" 
                               backgroundColor="White"&gt;
            &lt;XF.Grid margin="5"
               rowDefinitions="auto,*" columnDefinitions="*"&gt;
                   &lt;XF.StackLayout
                        backgroundColor="#34395A"
                        horizontalOptions="FillAndExpand"&gt;
                        &lt;XF.Label
                            horizontalTextAlignment="Center"
                            horizontalOptions="CenterAndExpand"
                            text="Coin Watch"
                            fontAttributes="Bold"
                            fontSize="28"
                            padding="10"
                            textColor="White"/&gt;
                    &lt;/XF.StackLayout&gt;
                    &lt;XF.Grid backgroundColor="lightgray" { ... XF.Grid.row(1)}&gt;
                        &lt;XF.Grid rowDefinitions="auto,*" columnDefinitions="*"&gt;
                            &lt;XF.Grid
                                columnDefinitions="*,150,100"
                                backgroundColor="#f04726"
                                heightRequest="30"
                                padding="2"&gt;
                                &lt;XF.Label
                                    { ... XF.Grid.column(0)}
                                    horizontalTextAlignment="Start"
                                    fontAttributes="bold"
                                    padding="5"
                                    text="Coin Name"
                                    textColor="White" /&gt;
                                &lt;XF.Label
                                    { ... XF.Grid.column(1)}
                                    horizontalTextAlignment="End"
                                    padding="0,5,50,0"
                                    fontAttributes="bold"
                                    text="Price"
                                    textColor="White"/&gt;
                                &lt;XF.Label
                                    { ... XF.Grid.column(2)}
                                    horizontalTextAlignment="Start"
                                    fontAttributes="bold"
                                    padding="5"
                                    text="Change"
                                    textColor="White" /&gt;
                            &lt;/XF.Grid&gt;
                            &lt;XF.Grid
                                { ... XF.Grid.row(1)}&gt;
                                &lt;XF.ListView itemsSource={Bind.oneWay(() =&gt; this.viewModel.coinList)}&gt;
                                    &lt;XF.ListView.itemTemplate&gt;
                                        &lt;XF.DataTemplate&gt;
                                            &lt;XF.ViewCell&gt;
                                                &lt;XF.Grid
                                                    columnDefinitions="*,150,100"
                                                    padding="5"
                                                    backgroundColor={Colors.white}&gt;
                                                    &lt;XF.Label
                                                        { ... XF.Grid.column(0)}
                                                        padding="5"
                                                        fontAttributes="bold"
                                                        textColor={Colors.black}
                                                        text={Bind.oneWay((x) =&gt; x.data.symbol)}/&gt;
                                                    &lt;XF.Label
                                                    { ... XF.Grid.column(1)}
                                                        padding="5,5,40,0"
                                                        fontAttributes="bold"
                                                        horizontalOptions="End"
                                                        horizontalTextAlignment="End"
                                                        textColor={Colors.black}
                                                        text={Bind.oneWay((x) =&gt; this.viewModel.format(x.data.priceUsd))} /&gt;
                                                    &lt;XF.Frame   { ... XF.Grid.column(2)}
                                                        padding="1"
                                                        cornerRadius="5"
                                                        hasShadow="false"
                                                        backgroundColor={Bind.oneWay((x) =&gt; Math.sign(x.data.changePercent24Hr) === -1 ? "#FFE1e1": "#EDF9f5")}
                                                        borderColor={Bind.oneWay((x) =&gt; Math.sign(x.data.changePercent24Hr) === -1 ? "#F76868": "#64CAAA")}&gt;
                                                    &lt;XF.StackLayout orientation="Horizontal"
                                                                padding="5"&gt;
                                                        &lt;XF.Image horizontalOptions="Center"&gt;
                                                            &lt;XF.Image.source&gt;
                                                                &lt;XF.FontImageSource
                                                                    color={Bind.oneWay((x) =&gt; Math.sign(x.data.changePercent24Hr) === -1 ? "#ff7060": "#41ba86")}
                                                                    size={20}
                                                                    fontFamily={FontAwesomeSolid}
                                                                    glyph={Bind.oneWay((x) =&gt; Math.sign(x.data.changePercent24Hr) === -1 ?
                                                                        FontAwesomeSolid.caretDown:
                                                                        FontAwesomeSolid.caretUp)}
                                                                    /&gt;
                                                            &lt;/XF.Image.source&gt;
                                                        &lt;/XF.Image&gt;
                                                        &lt;XF.Label
                                                            horizontalOptions="EndAndExpand"
                                                            horizontalTextAlignment="Center"
                                                            fontAttributes="Bold"
                                                            padding="0,0,10,0"
                                                            textColor={Bind.oneWay((x) =&gt; Math.sign(x.data.changePercent24Hr) ===-1 ? "#F76868": "#64CAAA")}
                                                            text={Bind.oneWay((x) =&gt; this.viewModel.formatPercentage(x.data.changePercent24Hr) )}&gt;
                                                        &lt;/XF.Label&gt;
                                                    &lt;/XF.StackLayout&gt;
                                                 &lt;/XF.Frame&gt;
                                           &lt;/XF.Grid&gt;
                                        &lt;/XF.ViewCell&gt;
                                        &lt;/XF.DataTemplate&gt;
                                    &lt;/XF.ListView.itemTemplate&gt;
                                &lt;/XF.ListView&gt;
                            &lt;/XF.Grid&gt;
                    &lt;/XF.Grid&gt;
                &lt;/XF.Grid&gt;
            &lt;/XF.Grid&gt;
        &lt;/XF.ContentPage&gt;);
    }
}
```
###See Also
[WebAtoms Xamarin Forms Fiddle](https://dev.to/web-atoms/introducing-xamarin-forms-fiddle-2h1i).
&lt;br/&gt;
[Full code example](https://www.webatoms.in/play/@web-atoms/sample-8e/8).


</description>
      <pubDate>Friday, September 10, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/85/Bitcoin2.jpg</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms-XFLIstView-Control-1Z</guid>
    </item>
    <item>
      <title>Major Version 1.6.239 Update with New Platforms</title>
      <link>https://www.webatoms.in/blog/web-atoms-updates/Major-Version-1-6-239-Update-with-New-Platforms-1Y</link>
      <author>Akash Kava</author>
      <description>## Major Version 1.6.239 Update

## New Platforms
We have added following new platform support.

1. UWP - Universal Windows Platform
2. MacOS
3. Tizen - * Community Support
4. GTK - * Community Support

* Xamarin does not support these platforms officially, however we will try to support as much as we can provided bug/update is part of Web Atoms framework.

### A New JavaScript Engine

We have written a new JavaScript Engine YantraJS specifically for Web Atoms, this engine is written in C#, so it can run anywhere wherever C# is supported, except iOS as it does not allow loading dynamic types.

### New Controls

1. AtomButtonBar - a native button bar
2. AtomCalendar - Calendar control to host date items
3. AtomDateField - A selectable date field built on top of AtomCalendar, native calendar is difficult to navigate, changing year requires many taps on android, but AtomCalendar provides nice drop down for easy change.
4. AtomChoiceView - A simple dropdown with ability to search and choose
5. AtomChips - multiple list items, editable, searchable

### Console Debugging Hints

1. `bridge.root`, while in debugger console, you can type `bridge.root` to inspect UI hierarchy
2. You can also use `bridge.root` in safari developer tools (Requires Mac)

### A new code Generator

We have released source code for TypeScript definition generator from dll, which you can use to generate source code of your custom UI Elements.

[GitHub  - TypeScript Definition Generator Link](https://github.com/web-atoms/TypeScript-Definition-Generator)

### UWP Sample

We have added UWP sample in `xf-samples` repository, https://github.com/web-atoms/xf-samples

### AtomPopup

We have added `AtomPopup` class which lets you create easy popups attached to any element. (Requires Grid in root of Page). You have to set `PopupTemplate` and `DisplayPopup` attached properties. `Popup` will be created and displayed as long as `DisplayPopup` is set to true.

### IJSContext.CreateBoundFunction

Creating bound functions in iOS are tricky, earlier every function was bound by default and extending C# class to JavaScript was slower. This was improved by introduction of `IJSContext.CreateBoundFunction` method, in which a delegate receives `this` parameter. In iOS, this function requires two steps, so you should use `IJSContext.CreateFunction` for faster execution. On other platforms it does not matter which one do you use.

</description>
      <pubDate>Thursday, September 9, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/79/Version-1.6.239-1.jpg</image>
      <guid>https://www.webatoms.in/blog/web-atoms-updates/Major-Version-1-6-239-Update-with-New-Platforms-1Y</guid>
    </item>
    <item>
      <title>Schema Migration: Entity Framework Core</title>
      <link>https://www.webatoms.in/blog/developer-guide/Schema-Migration-Entity-Framework-Core-1X</link>
      <author>Akash Kava</author>
      <description>[![.NET](https://github.com/neurospeech/ef-core-automatic-migration/actions/workflows/main.yml/badge.svg)](https://github.com/neurospeech/ef-core-automatic-migration/actions/workflows/main.yml)
# Automatic Migration support for EF Core
Entity Framework Core does not support automatic migration like earlier EntityFramework 6.x; Though it is useful feature, looks like it may not be implemented due to other priorities.

This library helps in running automatic migration against database with following features.

# Features

1. Creates Missing Table
2. Creates Missing Columns
3. Renames old column with same name, creates new column and migrates data if no loss occurs, you can customize this.
4. Renames old indexes and creates new ones
5. Creates indexes based on foreign keys
6. Entire migration runs in a single transaction, so if changes are large, they will fail and rolled back to previous state.

# Warning

1. Please test this toughly before using it in production, always take backup of your database before running migrations on production.
2. It is also recommended to run migrations separately with some conditions, so you are aware of what changes are being taken.
3. This library is essential in earlier stages of development, and should only be used for small changes like adding non existing tables/columns.

# Installation
## NuGet
| Name                               | Package                                                                                                                                                        |
|------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|
| NeuroSpeech.EFCoreAutomaticMigration               | [![NuGet](https://img.shields.io/nuget/v/NeuroSpeech.EFCoreAutomaticMigration.svg?label=NuGet)](https://www.nuget.org/packages/NeuroSpeech.EFCoreAutomaticMigration)                           |
| NeuroSpeech.EFCoreAutomaticMigration.PostGreSql         | [![NuGet](https://img.shields.io/nuget/v/NeuroSpeech.EFCoreAutomaticMigration.PostGreSql.svg?label=NuGet)](https://www.nuget.org/packages/NeuroSpeech.EFCoreAutomaticMigration.PostGreSql)               |


# Run
```c#

public void Configure(IApplicationBuilder app, IHostingEnvironment env){

	if(env.IsDevelopment()){
		app.UseDeveloperExceptionPage();

		using (var scope = app.ApplicationServices.GetService&lt;IServiceScopeFactory&gt;().CreateScope())
		{
			using (var db = scope.ServiceProvider.GetRequiredService&lt;AppModelContext&gt;())
			{
				db.MigrationForSqlServer()
					.Migrate(preventChangeColumn: true);
			}
		}
	}

}

```

# Change in existing Columns

Many times even slight change in model may result in changing of column schema, though there are two options in such case.

## Prevent Change 

This is the default option, in this case, the migration will fail.

## Manually Apply the Change

Lets assume we have made BrokerID optional and it needs to be updated as nullable in the schema. In this case we can run a simple alert statement manually to make migration smooth. This will happen only if the target schema is old. The condition will not execute if target contains exact same schema.

```c#
	db.MigrationForSqlServer()
	    .OnColumnChange((migration, existingColumn, currentColumn, tempName) =&gt; {
		     // you can use properties to run some migrations manually ...
			 if(existingColumn.TableNameAndColumnName == "[Product].[BrokerID]"
			     &amp;&amp; existingColumn.IsNullable != currentColumn.IsNullable) {
			     // since we just changed column to nullable.. we can simply run alter by ourselves...
				 migration.Run("ALTER TABLE [Product] ALTER COLUMN [BrokerID] INT NULL");
			 }
		})
		.Migrate();
	
```


</description>
      <pubDate>Tuesday, September 7, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/77/Linkedin-EF-Core-Automatic-Migrations.gif</image>
      <guid>https://www.webatoms.in/blog/developer-guide/Schema-Migration-Entity-Framework-Core-1X</guid>
    </item>
    <item>
      <title>WebAtoms with Font Awesome</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms-with-Font-Awesome-1w</link>
      <author>srikanth.naidu</author>
      <description>
##WebAtoms##

Web Atoms is an advanced MVVM framework to write cross platform applications in HTML5 and Xamarin.Forms.

##Font Awesome##

The internet's most popular icon toolkit has been redesigned and built from scratch. On top of this, features like icon font ligatures, an SVG framework, official NPM packages for popular frontend libraries like React, and access to a new CDN.

##Integration:##

WebAtoms Xamarin.Forms is now integrated with the Font Awesome, you can use any Font Awesome icons in any of the user interface controls that WebAtoms provide. It is easy to integrate the Font Awesome icons.

While working on Xamarin.Forms apps  we need to integrate Material Design Icons into the app, now with font awesome integration we can access a bunch of icons that are the same on each platform.

##Controls##

Buttons, Labels, List can be entitled with related icons.
		
**Properties**

Color: Color of the icon

Glyph : Icon source name


**Code for label:**
![image](/api/attachments/att/73/label.png)

**Code for button:**	![image](/api/attachments/att/74/button.png)


**Demo:**

![image](/api/attachments/att/75/sample-button.png)

 [Demo Link](https://www.webatoms.in/play/@web-atoms/sample-89/1)
 </description>
      <pubDate>Monday, August 30, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/76/webfontawesome.jpg</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms-with-Font-Awesome-1w</guid>
    </item>
    <item>
      <title>WebAtoms - AtomXFToggleButton Bar</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms-AtomXFToggleButton-Bar-1Q</link>
      <author>Ajay Singh</author>
      <description>In the [previous](https://www.webatoms.in/blog/tutorials/WebAtoms-AtomXFToggleButton-Bar-1N#contextId=0) article we have learnt how to create the **WebAtoms XFToggleButtonBar** user interface control.

But what if you want to customize it? In continuation to previous article, let's try to adapt the previous example for customizations.

In this post we will learn how we can create the `DataTemplate` for `XFToggleButtonBar` and integrate the `Font Awesome` icons in it. In the previous article we just shown the `value` in the control, now we will add some images in `XFToggleButtonBar` `Data Template`.

One of the best thing about `WebAtoms Xamarin.Forms` is that, we have integrated the [`Font Awesome`](https://fontawesome.com/) inside our framework, that means you can use any `Font Awesome` icons in any of the user interface control that **WebAtoms** provide. It is easy to integrate the Font Awesome icons.
 &lt;br/&gt;
Let's check in the below code snippet, We have added the `FontAwesomeSolid.female` and `FontAwesomeSolid.male` with `XF.Label`.

```javascript
 this.render(&lt;XF.ContentPage title="Custom Toggle Button Bar" backgroundColor="#FAFAFA"&gt;
                 &lt;XF.StackLayout padding="20" 
                    verticalOptions = "Center"
                    horizontalOptions = "Center"
                    HeightRequest = "200"
                    WidthRequest = "300" &gt;

                    &lt;XF.Label
                        fontAttributes="Bold"
                        textColor="black"
                        padding="0,15,0,5"
                        fontSize="25"
                        text="SELECT GENDER"/&gt;
         
                    &lt;AtomXFToggleButtonBar 
                        items={this.viewModel.genderList}
                        value={Bind.twoWays(() =&gt; this.viewModel.gender)}&gt;
                        &lt;AtomXFToggleButtonBar.itemTemplate&gt;
                            &lt;XF.DataTemplate&gt;
                            &lt;XF.Frame 
                                cornerRadius={5} 
                                padding={0} 
                                backgroundColor="transparent" 
                                borderColor={Colors.lightGray} &gt;
                                &lt;XF.StackLayout 
                                    orientation="Horizontal" 
                                    backgroundColor={Bind.oneWay((x) =&gt; x.data !== x.localViewModel.owner.selectedItem
                                            ? "#E0e0e0"
                                            : "#OC5FA3" )}&gt;
                                    &lt;XF.Label
                                        padding="5"
                                        fontSize={30}
                                        fontFamily={FontAwesomeSolid.toString()}
                                        text={Bind.oneTime((x) =&gt; /female/i.test(x.data.value)
                                            ? FontAwesomeSolid.female 
                                            : FontAwesomeSolid.male )}
                                        textColor={Bind.oneWay((x) =&gt; x.data === x.localViewModel.owner.selectedItem
                                        ? Colors.white
                                        : Colors.black )} /&gt;
                                    &lt;XF.Label 
                                        padding={10} 
                                        fontAttributes="Bold"
                                        text={Bind.oneTime((x)=&gt;x.data.label)}
                                        textColor={Bind.oneWay((x) =&gt; x.data === x.localViewModel.owner.selectedItem
                                            ? Colors.white
                                            : Colors.black )} 
                                         /&gt;                   
                                &lt;/XF.StackLayout&gt;
                                &lt;/XF.Frame&gt;
                            &lt;/XF.DataTemplate&gt;
                        &lt;/AtomXFToggleButtonBar.itemTemplate&gt;
                    &lt;/AtomXFToggleButtonBar&gt;
                    &lt;XF.Label
                        padding="0,15,0,5"
                        fontSize={20}
                        textColor="black"
                        fontAttributes="Bold"
                        text={Bind.oneWay(() =&gt; `You are ${this.viewModel.gender.toUpperCase()}`)}
                        /&gt;
                &lt;/XF.StackLayout&gt;
            &lt;/XF.ContentPage&gt;);
```

Our `ViewModel` part will remain same as we have shown in the [previous](https://www.webatoms.in/blog/tutorials/WebAtoms-AtomXFToggleButton-Bar-1N#contextId=0) article.
How do I download the App?
&lt;br/&gt; 
[**Introducing Xamarin.Forms Fiddle**](https://dev.to/web-atoms/introducing-xamarin-forms-fiddle-2h1i)

How do I run the App? 
**[Open Demo](https://www.webatoms.in/play/@web-atoms/sample-87/1)**



</description>
      <pubDate>Sunday, August 29, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/71/tab--1-.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms-AtomXFToggleButton-Bar-1Q</guid>
    </item>
    <item>
      <title>Developer Guide: Async Tips</title>
      <link>https://www.webatoms.in/blog/developer-guide/Developer-Guide-Async-Tips-1T</link>
      <author>Akash Kava</author>
      <description>###JavaScript/TypeScript Async Programming Tips  
&lt;br/&gt;

Please feel free to add more tips.

# Do not create async if only last return statement has await

```typescript

public async fetchList(): Promise&lt;T&gt; {

   return await this.someService.fetchList(...);

}

```

You can omit `async/await` here


```typescript

public fetchList(): Promise&lt;T&gt; {

   return this.someService.fetchList(...);

}

```

Both are logically same, unless compiler tries to optimize this automatically, you can simply avoid `async/await`.

# Do not omit `async/await` when catching exceptions...

In above example, if you want to catch an exception... following code is wrong...

```typescript

public fetchList(): Promise&lt;T&gt; {
   try {
      return this.someService.fetchList(...);
   } catch(e) {
       // report an error
      this.reportError(e);
      return Promise.resolve(null);
   }

}

```

This will never catch a network related error, following is the correct way.

```typescript

public async fetchList(): Promise&lt;T&gt; {
   try {
      return await this.someService.fetchList(...);
   } catch(e) {
       // report an error
      this.reportError(e);
      return null;
   }

}
```

# Use `Promise.all`

```typescript

   public async fetchDetails(list: IModel): Promise&lt;IDetail[]&gt; {
       const details = [];
       for(const iterator of list) {
           const result = await this.someService.fetchDetails(iterator.id);
           details.push(result);
       }
       return details;
   }
```

There is sequential operation and it will take long time, instead try this..


```typescript

   public fetchDetails(list: IModel): Promise&lt;IDetail[]&gt; {
       const details = list.map((item) =&gt; 
          this.someService.fetchDetails(item.id));
       return Promise.all(details);
   }
```

If you want to return null if any one fails, 


```typescript

   public fetchDetails(list: IModel): Promise&lt;IDetail[]&gt; {
       const details = list.map(async (item) =&gt; {
           try {
              return await this.someService.fetchDetails(item.id); 
           } catch (e) {
               this.reportError(e);
               return null;
           }
       });
       return Promise.all(details);
   }
```

## You can use `Promise.all` without an array as well

```typescript
   public async fetchDetails(): Promise&lt;void&gt; {
       this.userModel = await this.userService.fetchUser();
       this.billingModel = await this.billingService.fetchBilling();
       this.notifications = await this.notificationService.fetchRecent();
   }
```

You can rewrite this as,

```typescript
   public fetchDetails(): Promise&lt;void&gt; {
       [this.userModel, 
          this.billingModel,
          this.notifications] = Promise.all(
              [this.userService.fetchUser(),
              this.billingService.fetchBilling(),
              this.notificationService.fetchRecent()]);
   }
```


# Atomic Cached Promises

You can keep reference of previous promises as long as you wish to cache them and result of promise will be available for all future calls without invoking actual remote calls.

```typescript

   private cache: { [key: number]: [number, Promise&lt;IDetail&gt;] } = {};

   public fetchDetails(id: number): Promise&lt;IDetail&gt; {
      let [timeout, result] = this.cache[id];
      const time = (new Date()).getTime();
      if (timeout !== undefined &amp;&amp; timeout &lt; time {
         timeout = undefined; 
      }
      if (timeout === undefined) {
         // cache result for 60 seconds
         timeout = time + 60 * 1000;
         result = this.someService.fetchDetails(id);
         this.cache[id] = [timeout, result];
      }
      return result;
   }

```

This call is atomic, so for any given id, only one call will be made to remote server within 60 seconds.

# Delay

```typescript

   public static delay(seconds: number): Promise&lt;void&gt; {
       return new Promise((r,c) =&gt; {
           setTimeout(r, seconds * 1000);
       });
   }


   // usage...

   await delay(0.5);

```

# Combining Delay with Cancellation

If we want to provide interactive search when results are displayed as soon as someone types character but you want to fire search only when there is pause of 500ms, this is how it is done.

```typescript

   public cancelToken: { cancelled: boolean } = null;   

   public fetchResults(search: string): Promise&lt;IModel[]&gt; {
       if (this.cancelToken) {
           this.cancelToken.cancelled = true;
       }
       const t = this.cancelToken = { cancelled: false };
       const fetch = async () =&gt; {
           await delay(0.5);
           if(t.cancelled) {
              throw new Error("cancelled");
           }
           const r = await this.someService.fetchResults(search);
           if(t.cancelled) {
              throw new Error("cancelled");
           }
           return r;
       };
       return fetch();
   }

```

This method will not call remote API if the method would be called within 500ms.

but there is a possibility of it being called after 500ms. In order to support rest API cancellation, little bit more work is required.

# CancelToken class

```typescript
export class CancelToken {

    private listeners: Array&lt;() =&gt; void&gt; = [];

    private mCancelled: boolean;
    get cancelled(): boolean {
        return this.mCancelled;
    }

    public cancel(): void {
        this.mCancelled = true;
        const existing = this.listeners.slice(0);
        this.listeners.length = 0;
        for (const fx of existing) {
            fx();
        }
    }

    public registerForCancel(f: () =&gt; void): void {
        if (this.mCancelled) {
            f();
            this.cancel();
            return;
        }
        this.listeners.push(f);
    }

}
```

## Api Call needs some work... given an example with XmlHttpRequest

```typescript

   public static delay(n: number, c: CancelToken): Promise&lt;void&gt; {
      return new Promise((resolve, reject) =&gt; {
         let timer = { id: null };
         timer.id = setTimeout(() =&gt; {
            timer.id = null;
            if(c.cancelled) {
                reject("cancelled");
                return;
            }
            resolve();
         }, n * 1000);
         c.registerForCancel(() =&gt; {
            if( timer.id) { 
               clearTimeout(timer.id);
               reject("cancelled");
            }
         });
      });
   }

   public async ajaxCall(options): Promise&lt;IApiResult&gt; {

      await delay(0.1, options.cancel);

      const xhr = new XMLHttpRequest();

      const result = await new Promise&lt;IApiResult&gt; ((resolve, reject)) =&gt; {

         if (options.cancel &amp;&amp; options.cancel.cancelled) {
             reject("cancelled");
             return;
         }

         if (options.cancel) {
             options.cancel.registerForCancel(() =&gt; {
                xhr.abort();
                reject("cancelled");
                return;
             });
         }
         
         // make actual call with xhr...

      });

      if (options.cancel &amp;&amp; options.cancel.cancelled) {
          throw new Error("cancelled");
      }
      return result;

   }

```

This can cancel requests that were cancelled by user as soon as he typed new character after 500ms. 

This cancels existing calls, browser stops processing output and browser terminates connection, which if server is smart enough to understand, also cancels server side processing.

# For best use, you can combine all the tips and create best UX</description>
      <pubDate>Friday, August 27, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/68/Asynhronous-Programming-Tips.gif</image>
      <guid>https://www.webatoms.in/blog/developer-guide/Developer-Guide-Async-Tips-1T</guid>
    </item>
    <item>
      <title>JavaScript/TypeScript Development Guidelines</title>
      <link>https://www.webatoms.in/blog/developer-guide/JavaScript-TypeScript-Development-Guidelines-1S</link>
      <author>Simmi Kava</author>
      <description>### Coding Guidelines  
&lt;br/&gt;

- Use `module` pattern whenever possible. But do you know the reason why? Let me explain it to you.   
&lt;br/&gt;
--  Modules are executed within their own scope and not in global scope. 

  --  Code reusability.

  --  Encapsulation

  --  Load on demand

  --  Easier testing

- Avoid using `namespace` if modules is a possibility. Why?
As you might end up importing the whole standard namespace into your program which may not be required.

- Organize single class into a single file. 

- Import only required module and retain naming convention.
- Use `default export` for 1 major class and `named export` for less frequent or related classes
- Refrain from using `underscore (_)` anywhere, not in field name  or get/set. Why?
As such a naming convention indicates a name is meant for internal use. **`TSLint`** doesn't respect the underscore pattern naming convention. 

- Do not create `async` if only last return statement has `await`. Do not omit `async/await` when catching exceptions. 

Will share another article on `async tips` soon! Till then happy learning. 

</description>
      <pubDate>Thursday, August 26, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/67/Linkedin-600-314-JS-TS-Coding-Guidelines.gif</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JavaScript-TypeScript-Development-Guidelines-1S</guid>
    </item>
    <item>
      <title>Good words of Wisdom</title>
      <link>https://www.webatoms.in/blog/general/Good-words-of-Wisdom-1R</link>
      <author>Simmi Kava</author>
      <description>### Wise Thoughts for the Day  
&lt;br/&gt;

Easier said than done, we all know it! But let's strive for the progress and not flawlessness and excellence. **Focus, Patience** and connecting with the ultimate **Purpose** should be your goal!

Just keep going relentlessly, even if it is bit by bit, focus on the purpose and patiently keep doing your work to achieve your ultimate purpose. 

Hope this helps!</description>
      <pubDate>Tuesday, August 24, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/66/Breathe-Animation-TextOnly-All.gif</image>
      <guid>https://www.webatoms.in/blog/general/Good-words-of-Wisdom-1R</guid>
    </item>
    <item>
      <title>Drawbacks of Compiled Languages</title>
      <link>https://www.webatoms.in/blog/developer-guide/Drawbacks-of-Compiled-Languages-1P</link>
      <author>Akash Kava</author>
      <description>Compiled languages like **C, C++, Java, C#** and many others claimed for faster performance stayed behind in popularity and adoption compared to **JavaScript, PHP, Python etc.** This article is focused more on small business applications and prototype products.

It appears just faster performance is not enough for every product. 

# Slow compilation time
Compiled languages outperform scripted languages when executing, but compilation time is slower. So creating and distributing product is often very slow. For example, **Chromium** written in **C++** to build Chrome browser is very huge and compiling and running all unit tests span couple of hours.

# Different binaries
Compiled languages binaries are different for each type of CPU/Device Architecture, though **Java** and **.NET** tried to solve it using intermediate binaries, but there are always many issues at runtime. So the distributions become large in file size and interdependencies become very high. And size of source code is often small compared to binaries.

# Strict Typing
Most compiled languages often have very strict typing restrictions, which makes source code very large and every type of business data requires huge set of metadata to deal with (e.g. classes and properties). And often little mismatch in type in dependent library can halt entire project.

# Slow loading
This might sound wrong, but compiled binaries are loaded all in memory even if you are going to execute code from one single file. **Java** has solved this by choosing one file per class and by allowing executing single class file. But in **C/C++/C#** all need to load entire module to start executing the code. Where else single file based scripts are easy to load and run as it will only execute the imported files instead of all the files of the project. Though you can achieve this in compiled languages but it requires lot of maintenance and extra code to do everything.

# Difficult to debug in Production
Compiled binaries are often very difficult to debug, leading to crash and in production, **Java, .NET**, and every other compiled languages strip off debug symbols being too big. Which leads to nightmare in finding root cause of errors in production. There are ways to include debug symbols, but often when you deal with third party libraries without symbols. **.NET** also tries to load and compile relevant files only as needed, but version mismatch can prevent entire application from loading.

# Difficult to Prototype
If product requirements are changing constantly due to changes in the market, or a new product is designed by research team, slow build time can exponentially delay the product. This was the primary reason for people to adopt **Python, PHP and JavaScript** over **Java, C#** for web projects. **.NET** is trying to catch up here, but it still has slow botting time, and lack of source code is often roadblock in debugging.

# Lack of source code
Products shipped with compiled binaries do not ship source code, and they are often hidden to enforce licensing, but it makes it extremely difficult to find bugs. 

On other hand, **Python, PHP, JavaScript** are distributed in the source form, even third party libraries (unless they are compiled to native for performance) are also shipped in source code form. Which makes it easier to analyze bugs.

Also dynamic typing reduces overhead of type checking at compile time, if the dependent code isn't used which has type mismatch, other code will still work correctly.</description>
      <pubDate>Monday, August 23, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/65/Drawbacks-compiled-langugage.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/Drawbacks-of-Compiled-Languages-1P</guid>
    </item>
    <item>
      <title>Take a BR-eak</title>
      <link>https://www.webatoms.in/blog/general/Take-a-br-1M</link>
      <author>Simmi Kava</author>
      <description>###&lt; br/&gt;  
&lt;br/&gt;

Sometimes it's okay to take a break `&lt;br/&gt;` and connect with yourself, almost everything will resume if you unplug yourself for few moments. 


```javascript
async improve() {
   await break(time);
   return [productivity++, creativity++];
}
```

Always remember exhibiting positive energy is contagious! :-) 

Have a good day.</description>
      <pubDate>Tuesday, August 17, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/57/Linkedin-WebAtoms.png</image>
      <guid>https://www.webatoms.in/blog/general/Take-a-br-1M</guid>
    </item>
    <item>
      <title>WebAtoms - AtomXFToggleButton Bar</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms-AtomXFToggleButton-Bar-1N</link>
      <author>Ajay Singh</author>
      <description>Today we are going to have a look on 
the `WebAtoms` Xamarin.Forms  **AtomXFToggleButtonBar** user interface control. &lt;br/&gt;&lt;br/&gt;
Let's first briefly check what is `WebAtoms`? 

&lt;br/&gt;
 [WebAtoms] (https://www.webatoms.in/index.html) is an advanced MVVM framework to write cross platform applications in `Xamarin.Forms`. Unlike other frameworks, `WebAtoms` lets you divide User Interface logic in strict MVVM fashion and separates View in `XAML`. Benefit of separating User interface logic in `ViewModel` is you can individually unit test view model to make sure your logic is consistent across platforms.
 
####Xamarin Fiddle 
&lt;br/&gt;
[Check out this] (https://dev.to/web-atoms/introducing-xamarin-forms-fiddle-2h1i)
 
Now we will see the actual implementation of `WebAtoms` Xamarin.Forms user interface control **AtomXFToggleButtonBar**.
This control allow users to take actions, and make choices, with a single tap. &lt;br/&gt;
 **View** 

```javascript
export default class MainPage extends AtomXFContentPage {
 
    public viewModel: MainPageViewModel;
 
    public create() {
 
        this.viewModel = this.resolve(MainPageViewModel);
 
        this.render( &lt;XF.ContentPage title="Toggle Button Bar" backgroundColor="white"&gt;
                &lt;XF.StackLayout padding="20"&gt;
 
                      &lt;XF.Label horizontalTextAlignment="center"
                        fontSize="40"
                        text="GENDER"
                        /&gt;
 
                    &lt;AtomXFToggleButtonBar
                        items={this.viewModel.genderList}
                        value={Bind.twoWays(() =&gt; this.viewModel.gender)}
                        /&gt;
                    &lt;XF.Label padding="10"
                        fontSize="25"
                        text={Bind.oneWay(() =&gt; `Selected gender is ${this.viewModel.gender.toUpperCase()}`)}
                        /&gt;
                &lt;/XF.StackLayout&gt;
            &lt;/XF.ContentPage&gt;
              );
    }
 
}
```
This above code snippet is easy to understand, `items` property of control bind the items which will come from `ViewModel` and the `value` property will tell us the toggle button selected by the user. There are different ways of [bindings](https://dev.to/web-atoms/different-types-of-bindings-in-web-atoms-for-xamarin-forms-4bf4) available in `WebAtoms` Xamarin forms.

**ViewModel**
 
```javascript
import { AtomViewModel } from "@web-atoms/core/dist/view-model/AtomViewModel";
 
export default class MainPageViewModel extends AtomViewModel {
 
     public genderList = [
        { label: "Male", value: "male" },
        { label: "Female", value: "female" }
    ];
 
    public gender = "female";}
```
The public property `gender` and the `genderlist` will be bound to the **AtomXFToggleButtonBar** control in above view.&lt;br/&gt;
So now you know how to create a **AtomXFToggleButtonBar** in `WebAtoms`.


 
</description>
      <pubDate>Tuesday, August 17, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/64/webatoms.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms-AtomXFToggleButton-Bar-1N</guid>
    </item>
    <item>
      <title>WebAtoms - Action Decorator</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms-Action-Decorator-1K</link>
      <author>Simmi Kava</author>
      <description># Action

`@Action` decorator can be applied on a method which will automatically display an alert if there was any error. And it will invoke validation before executing the method. Display an success alert after completion if configured. You can also configure `confirm` to request confirmation (e.g. for delete operations).

```typescript
export default class SignupViewModel extends AtomViewModel {

    /** This decorator will handle validation, display error
     * and will display an alert for success
     */
    @Action({
        validate: true,
        success: "Signup successful",
        confirm: false,
    })
    public async signup() {
        ....
    }

}
```
```typescript
    &lt;XF.Button
        command={Bind.event((e) =&gt;
            this.viewModel.signup())}
        text="Signup"
        /&gt;
```


</description>
      <pubDate>Monday, August 16, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/56/Action-Decorator.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms-Action-Decorator-1K</guid>
    </item>
    <item>
      <title>Trampoline</title>
      <link>https://www.webatoms.in/blog/general/Trampoline-1J</link>
      <author>Simmi Kava</author>
      <description>### What is a Trampoline function?
&lt;br/&gt;
In **Computer Programming**, trampoline is associated with Jump Instructions i.e. moving to different code paths. 

In functional programming, a trampoline is a loop that iteratively invokes thunk-returning functions. i.e. instead of making a recursive call to a function, we return an instruction (thunk) to call that function, to be interpreted in a loop. 

Trampoline calls the recursive function in pieces until it no longer produces iterative/recursive calls. It takes recursive function as its argument, wraps it and returns a new function. Within the new function, the recursive function is called. The loop keeps running until function resolves into a value. 

**Use:** To implement tail-recursive calls in stack-oriented programming languages.

**References:**
[Blog Article1](https://blog.logrocket.com/using-trampolines-to-manage-large-recursive-loops-in-javascript-d8c9db095ae) |
[Article 2](http://www.thinkingincrowd.me/2016/06/06/How-to-avoid-Stack-overflow-error-on-recursive/)
</description>
      <pubDate>Tuesday, August 10, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/55/Linkedin-What-is-a-Trampoline-Function.png</image>
      <guid>https://www.webatoms.in/blog/general/Trampoline-1J</guid>
    </item>
    <item>
      <title>WebAtoms: WATCH &amp; VALIDATE Decorators</title>
      <link>https://www.webatoms.in/blog/tutorials/WebAtoms-WATCH-VALIDATE-Decorators-1H</link>
      <author>Simmi Kava</author>
      <description>### WebAtoms Decorators - Watch &amp; Validate   
&lt;br/&gt;

## Watch Decorator

Watching property is super easy with Web Atoms. You can simply create a readonly accessor and mark it is `@Watch`.

```typescript
export default class EditorViewModel extends AtomViewModel {

    public model: CustomerModel = {
        firstName: "",
        lastName: ""
    };

    @Watch
    public get fullName() {
        const firstName = this.model.firstName;
        const lastName = this.model.lastName;
        return firstName + " " + lastName;
    }
}
```
Usage
```typescript
    this.render(&lt;WA.AtomForm&gt;
        &lt;WA.AtomField&gt;
            &lt;XF.Entry text={Bind.twoWays(() =&gt;
                this.viewModel.model.firstName)}&gt;
        &lt;/WA.AtomField&gt;
        &lt;WA.AtomField&gt;
            &lt;XF.Entry text={Bind.twoWays(() =&gt;
                this.viewModel.model.lastName)}&gt;
        &lt;/WA.AtomField&gt;
        &lt;WA.AtomField&gt;
            &lt;XF.Label text={Bind.oneWay(() =&gt; this.viewModel.fullName)}&gt;
        &lt;/WA.AtomField&gt;
    &lt;/WA.AtomForm&gt;);
```

# Validate Decorator

`Validate` is special type of watch, which gets activated only if validation was requested. You can simply mark the getter property as `@Validate`.

```typescript
export default class SignupViewModel extends AtomViewModel {
    public model: CustomerModel = {
        firstName: "",
        lastName: "",
        emailAddress: ""
    };

    @Validate
    public get errorFirstName() {
        if (!this.model.firstName) {
            return "First name is required";
        }
        return "";
    }

    @Validate
    public get errorEmailAddress() {
        const email = this.model.emailAddress;
        if (!email) {
            return "Email is required"; 
        }
        if (!emailRegEx.test(email)) {
            return "Invalid email";
        }
        return "";
    }

    @Action({ validate: true })
    public async actionSignup() {
        // only when this was invoked
        // in UI, validation occurs
    }
}
```

```typescript
export default class Signup extends AtomXFContentPage {

    public viewModel: SignupViewModel;
    
    public create() {
        
        this.viewModel = this.resolve(SignupViewModel);

        this.render(&lt;WA.AtomForm&gt;
            &lt;WA.AtomField&gt;
                &lt;XF.Entry text={Bind.twoWays(() =&gt;
                    this.viewModel.model.firstName)}&gt;
            &lt;/WA.AtomField&gt;
            &lt;WA.AtomField&gt;
                &lt;XF.Entry text={Bind.twoWays(() =&gt;
                    this.viewModel.model.emailAddress)}&gt;
            &lt;/WA.AtomField&gt;
            &lt;WA.AtomField&gt;
                &lt;XF.Button
                    command={Bind.event(() =&gt; this.viewModel.actionSignup())}
                    text="Signup"&gt;
            &lt;/WA.AtomField&gt;
        &lt;/WA.AtomForm&gt;);
    }
}    
```
</description>
      <pubDate>Monday, August 9, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/54/watch-validate-webatoms-decorartos.gif</image>
      <guid>https://www.webatoms.in/blog/tutorials/WebAtoms-WATCH-VALIDATE-Decorators-1H</guid>
    </item>
    <item>
      <title>JS: hasOwnProperty vs Truthy vs in</title>
      <link>https://www.webatoms.in/blog/developer-guide/JS-hasOwnProperty-vs-Truthy-vs-in-1G</link>
      <author>Akash Kava</author>
      <description>###JavaScript: hasOwnProperty vs Truthy vs in
&lt;br/&gt;

In JavaScript we often check if property exists or not on the object to make some decision, for example lets look at the following code:-


## HasOwnProperty

```javascript
function process(c) {
    if(c.hasOwnProperty("element")) {
       ... do something
       return;
    }
    ... do something otherwise...
}
```

But it turns out that it is very slow, as `hasOwnProperty` lives in the prototype of `Object`. So if `c` is an array, 
1. JavaScript engine will first check if `hasOwnProperty` exists in `c` itself
2. Then it will check in `Array.prototype`.
3. And finally it will fetch the function from `Object.prototype` and then call method by passing `this` and parameter `element`.

Note, the steps 1,3 will have many intermediate prototype checks if `c` is basically a subclass of subclass of subclass of something.

## Check for Truthy

Another faster alternative is
```javascript
function process(c) {
    if(c.element)) {
       ... do something
       return;
    }
    ... do something otherwise...
}
```

This is called checking for `Truthy`, if an object is not **_zero/false/null/undefined or empty string_**, then it is considered as a `true`.

However, this is faster, but this is not same as `hasOwnProperty`, `c.element` will be false if `c` has the property `element` but it is **_zero/false/null/undefined or empty string_**.

## Check for _not undefined_

So we can change it to,
```javascript
function process(c) {
    if(c.element !== undefined)) {
       ... do something
       return;
    }
    ... do something otherwise...
}
```

This will determine if the `c` has property or not. But this still has a problem, `c.element` will not be undefined, even if `c` does not have `element` but its prototype has it.

And if `c` has a `element` getter, and if it returns `undefined`, the logic will still fail.

## Check using `in`

```javascript

function process(c) {
    if("element" in c) {
       ... do something
       return;
    }
}
```

This will check if `element` exists in `c` or it's prototype chain. It will return `true` irrespective of property value, as it will not evaluate the property, it will only check if any member exists with same name or not. It will return `true` if it has an empty accessor.

## Examples

```javascript

class A {
   get a() {
      return undefined;
   }
}

class B extends A {
   get b() { 
      return 1;
   }
}

var r = new B();
r.c = 0;

console.log(!! r.a);
// prints false

console.log(!! r.b);
// prints true

console.log(!! r.c);
// prints false

console.log("a" in r);
// prints true

console.log("b" in r);
// prints true

console.log("c" in r);
// prints true

console.log(r.hasOwnProperty("a"));
// prints false

console.log(r.hasOwnProperty("b"));
// prints false

console.log(r.hasOwnProperty("c"));
// prints true

```

## Summary
|                                                              | hasOwnProperty | Truthy     | Check for Undefined | in          |
|--------------------------------------------------------------|----------------|------------|---------------------|-------------|
| Checks if property exists in the object only                 | Yes            | No         | No                  | No, see 1.  |
| Checks if property is true                                   | No             | Yes        | No                  | No,  see 2. |
| Checks if property exists in the object or in the base class | No             | No, see 3. | No, see 4.          | Yes         |


1. It may return `true` if property exists in base class, it does not check if it is `true`.
2. It only checks if property exists in the same or base class, it does not check if it is `true`.

3. As property may exist but value may be `false`.

4. As getter may exist but value may return `undefined`.</description>
      <pubDate>Thursday, August 5, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/53/Linkedin-hasownproperty-truthy-in.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JS-hasOwnProperty-vs-Truthy-vs-in-1G</guid>
    </item>
    <item>
      <title>WebAtoms: Load Decorator &amp; Debouncing</title>
      <link>https://www.webatoms.in/blog/developer-guide/WebAtoms-Load-Decorator-Debouncing-1F</link>
      <author>Simmi Kava</author>
      <description>###What are Function/Method Decorators?

Function decorators allow us to add extra feature to your existing function i.e. it allows to change behavior of your existing function at compile time.  
&lt;br/&gt;


###WebAtoms: Load Decorator

Load decorator makes loading of async data very easy. Let's assume that we want to load countries and then selected state. It reports exceptions and cancels previous
operation.

```javascript
export default class SignupViewModel extends AtomViewModel {

    /** This gets called on initialization */
    @Load({ init: true })
    public async loadCountries() {
        this.countries = 
            await this.restService.getCountries();
        this.selectedCountry = this.countries
            .find((x) =&gt; x.value === "IN").value;
    }

    /** This gets called when `this.selectedCountry` changes */
    @Load({ watch: true /* watch */ })
    public async loadStates(ct: CancelToken) {
        const country = this.selectedCountry;
        // pass cancel token
        // to automatically cancel previous
        // incomplete request
        this.states = 
            await this.restService.getStates(country, ct);
    }

}
```
If you look in the above logic, we have a decorator `@Load({init: true})`, which will be executed during the initialization (`only once`) of view model _(we can use `init` on multiple methods)_ and another `@Load({watch:true})`, which will watch for changes in the country selected and fire the next operation  i.e. getting the `states` based on `country` selected. 

###What is Debouncing?

It is a programming technique to limit the number of times a long-drawn-out function gets called, which stalls the performance of your web page. 


###How can we achieve Debouncing using WebAtoms? 
Let's look at the example below. 

```javascript
export default class SignupViewModel extends AtomViewModel {

    @Load({
        /** watch for changes */
        watch: true,
        /** wait as user might still be typing */
        watchDelayInMS: 500
    })
    public async loadCities(ct: CancelToken) {
        const search = this.search;

        /** cancellation of previous request is tracked here */
        this.cities = await
            this.restService.searchCities(search, ct);
    }

}
```
As we look in the above logic, we are watching for any changes (user input) to the `City`. We have introduced a delay of 500ms as user might still be typing, `ct` is a cancel token which is tracked and only the last call result is returned i.e. if the debounced method/function is called only the latest call will result in the method call, the other ones will be discarded thereby limiting the number of times the method is invoked and improving the performance. 
</description>
      <pubDate>Wednesday, August 4, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/52/load-decorator-debouncing.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/WebAtoms-Load-Decorator-Debouncing-1F</guid>
    </item>
    <item>
      <title>JavaScript: CURRYING</title>
      <link>https://www.webatoms.in/blog/developer-guide/JavaScript-CURRYING-1E</link>
      <author>Simmi Kava</author>
      <description>###What is currying in JS? 


Currying is a process of evaluating a function with multiple arguments and turning it into a sequence of functions, each with single argument only i.e converting an **_n-ary_** function into the **_unary_** function form.  
&lt;br/&gt;

###Why use currying? 

1. Code reusability
2. To achieve Function Composition (A process of combining simple functions to build more complicated ones)
3. Easy to maintain as our code implementation will be smaller and more readable. 


**Can you explain it with an Example?**

Certainly,

_Let's look at an example to convert an input number to string using the radix provided._ 



```javascript
//Without Currying
var print = (number,radix) =&gt; number.toString(radix);
console.log(print(123,16)); //7b
console.log(print(123,2)); //1111011
```

```javascript
//With Currying
var print = (radix)  =&gt; (number) =&gt; number.toString(radix);
var hex = print(16);
var binary = print(2);
console.log(hex(123)); //"7b"
console.log(binary(123)); //"1111011"
```

Here, `print` is a function, which takes 1 argument which is `radix`, (16 for hex and 2 for binary etc.). `number` is the input number which needs to be converted and the `lambda function` will print the input number in the given numeral format.</description>
      <pubDate>Monday, August 2, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/51/Linkedin-Currying.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JavaScript-CURRYING-1E</guid>
    </item>
    <item>
      <title>Fetch GitHub User profile using WebAtoms - Xamarin.Forms.</title>
      <link>https://www.webatoms.in/blog/tutorials/fetch-GitHub-users-Information-1D</link>
      <author>Ajay Singh</author>
      <description>### A Xamarin.Forms simple app example: Fetch GitHub users information via API
&lt;br/&gt;
Very simple example of a **XAMARIN.FORMS** that accepts a GitHub username and once it receives username, it asks the GitHub API for the user information, and prints them.

##Code
Before proceedings to our code example let`s first understand what is **Web Atoms**.

**[Web Atoms](https://www.webatoms.in/index.html#contextId=1)**  is an advanced **MVVM framework** to write **cross platform applications** in **HTML5** and **Xamarin.Forms**.

We start by creating the class **MainPage.tsx**, the one that will display our image and details as gathered from GitHub.

This is our **View**.

```javascript
export default class MainPage extends AtomXFContentPage {

    public viewModel: MainPageViewModel;

    public create() {

        this.viewModel = this.resolve(MainPageViewModel);

        this.render(
            &lt;XF.ContentPage title="Github Profile"&gt;
                &lt;XF.StackLayout padding={20} &gt;
                   &lt;XF.SearchBar
                        text={Bind.twoWays((x) =&gt; this.viewModel.login)}
                        placeholder="Type username"
                        textColor="#1a4e8e"
                        placeholderColor="#1a4e8e"
                        backgroundColor="#e6ebed"/&gt;
                         &lt;XF.Frame 
                            padding="0"
                            margin="0,20,20,20"
                            horizontalOptions="CenterAndExpand"
                            verticalOptions="Center"
                            cornerRadius="100"
                            isClippedToBounds="true"
                            heightRequest="170"
                            widthRequest="170"
                            backgroundColor="transparent"&gt;
                        &lt;XF.Image 
                            source = {Bind.oneWay(()=&gt; this.viewModel.model.avatar_url)}
                            verticalOptions="FillAndExpand"
                            horizontalOptions="FillAndExpand"/&gt;
                         &lt;/XF.Frame&gt;   
                        &lt;XF.Label 
                            textColor="#1a4e8e"
                            fontSize="20"
                            fontAttributes="bold"
                            horizontalOptions="Center" horizontalTextAlignment="Center"
                            text = {Bind.oneWay(() =&gt; this.viewModel.model.name )} /&gt;
                        &lt;XF.Label 
                            textColor="Black"
                            fontSize="18"
                            fontAttributes="bold"
                            horizontalOptions="Center" horizontalTextAlignment="Center"
                            text = {Bind.oneWay(() =&gt; this.viewModel.model.location )} /&gt;

                         &lt;XF.Grid padding="15,35,5,5" margin= "0,20,0,0" backgroundColor="#1a4e8e" &gt;
                                &lt;XF.Grid.columnDefinitions &gt;
                                    &lt;XF.ColumnDefinition width="25*" /&gt;
                                    &lt;XF.ColumnDefinition width="25*" /&gt;
                                    &lt;XF.ColumnDefinition width="25*" /&gt;
                                &lt;/XF.Grid.columnDefinitions&gt;
                                &lt;XF.Grid.rowDefinitions&gt;
                                    &lt;XF.RowDefinition height="30"  /&gt;
                                    &lt;XF.RowDefinition height="30" /&gt;
                                    &lt;XF.RowDefinition height="30" /&gt;
                                &lt;/XF.Grid.rowDefinitions&gt;
                            &lt;XF.Label 
                                fontSize="24" 
                                horizontalOptions="Center" 
                                horizontalTextAlignment="Center"
                                textColor="White" 
                                fontAttributes="bold" 
                                text={Bind.oneWay(() =&gt; this.viewModel.model.following)} /&gt;
                            &lt;XF.Label {... XF.Grid.column(1)} 
                                fontSize="24" 
                                textColor="White" 
                                horizontalOptions="Center" 
                                horizontalTextAlignment="Center" 
                                fontAttributes="bold" 
                                text={Bind.oneWay(() =&gt; this.viewModel.model.public_repos)} /&gt;
                            &lt;XF.Label {... XF.Grid.column(2)} 
                                fontSize="24" 
                                textColor="White" 
                                fontAttributes="bold" 
                                horizontalOptions="Center" 
                                horizontalTextAlignment="Center"  
                                text={Bind.oneWay(() =&gt; this.viewModel.model.followers)} /&gt;
                            &lt;XF.Label {... XF.Grid.row(1)} 
                                textColor="#2776d7" 
                                text="Following" 
                                horizontalOptions="Center" 
                                horizontalTextAlignment="Center"  /&gt;
                            &lt;XF.Label 
                                {...XF.Grid.column(1)} 
                                {...XF.Grid.row(1)} 
                                text="Repository" 
                                textColor="#2776d7" 
                                horizontalOptions="Center" 
                                horizontalTextAlignment="Center"  /&gt;
                            &lt;XF.Label 
                                {...XF.Grid.column(2)} 
                                {...XF.Grid.row(1)} 
                                text="Follower" 
                                textColor="#2776d7" 
                                horizontalOptions="Center"
                                horizontalTextAlignment="Center"  /&gt;
                        &lt;/XF.Grid&gt;
                &lt;/XF.StackLayout&gt;
            &lt;/XF.ContentPage&gt;);
    }

}
```
The next part is **ViewModel**.
```javascript
export default class MainPageViewModel extends AtomViewModel {

    public model: IProfileModel;
    public login: string ="";

    @Inject
    private profileService: ProfileService;

    @Load({init: true, watch:true, watchDelayMS:1000})
    public async loadProfile(){
        this.model = await this.profileService.getProfile(this.login);
        this.login="";
    } 
}

```
Cool! We must have a way now to ask GitHub for the details of a single username. and we ask GitHub for information about a user using their public APIs,:

Look at the  **service** declaration.
```javascript

 @DISingleton()
 @BaseUrl("https://api.github.com/users/")
 export default class ProfileService extends BaseService {

  @Get("{login}")
  public getProfile( 
        @Path("login") login: string): Promise&lt;IProfileModel&gt; {
        return null;
    }
}
```
As easy as it looks, its very easy to configure REST service.

The last part is our **Model**.
```javascript
export default interface IProfileModel {
    location?: string;
    id?: number;
    avatar_url?: string;
    name?:string;
    html_url?:string;
    followers?: number;
    public_repos?: number;
    following?: number;
};
```

**Output** 
&lt;br/&gt;
&lt;br/&gt;
![image](/api/attachments/att/49/profile.jpg)</description>
      <pubDate>Friday, July 30, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/50/Twitter-image.png</image>
      <guid>https://www.webatoms.in/blog/tutorials/fetch-GitHub-users-Information-1D</guid>
    </item>
    <item>
      <title>JavaScript: Temporal Dead Zone (TDZ)</title>
      <link>https://www.webatoms.in/blog/developer-guide/JavaScript-Temporal-Dead-Zone-TDZ-1C</link>
      <author>Simmi Kava</author>
      <description>###What is Temporal Dead Zone (TDZ)?  
&lt;br/&gt;
TDZ is a term to describe the state of variables where they are not accessible. A variable declared using `let`  &amp; `const` is in TDZ from the start of the block until the initialization has completed.

A variable defined using `let` cannot be read/written until they have been full initialized. If no initial value provided, defaults to `undefined`.

Whereas, variables declared using the keyword `var` will return a value of `undefined` if accessed before declaration. 

```javascript
{ //TDZ starts at beginning of scope
console.log(framework); // Returns: undefined
console.log(ranking); // Returns: ReferenceError
var framework = "WebAtoms";
let ranking = "#1"; //TDZ ends here (for ranking)
}
```

The term `"temporal"` is used because the zone depends on the time it is executed (order of execution) rather than position(order) where it is declared. 

**Q) What will happen if we use typeOf operator on a variable which is in TDZ?**  

A: It will throw a Reference Error.  But when a `typeOf` operator is used on a undeclared or undefined variable, no error is thrown. 

[MDN Reference Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) 

Have a nice day!

</description>
      <pubDate>Tuesday, July 27, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/47/Linkedin-TDZ.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JavaScript-Temporal-Dead-Zone-TDZ-1C</guid>
    </item>
    <item>
      <title>Templated Query for TypeScript</title>
      <link>https://www.webatoms.in/blog/developer-guide/Templated-Query-for-TypeScript-1B</link>
      <author>Simmi Kava</author>
      <description>###Tagged Templates and Template Query  
&lt;br/&gt;


**What are Tagged Templates?**  


&amp;check; Advanced form of Template Literals  

&amp;check; Parse Template literal with a function  

&amp;check; First argument is array of strings. Remaining arguments are related to the expressions  

&amp;check; Tag function need not return a string  

&amp;check; `raw` property allows us to access the raw strings as it is i.e. as they were entered without the escape sequence.   

&amp;check; Use `String.raw()` method to create the raw strings   

**_Example:_**

```javascript
//Templated Query for TypeScript

const where = TemplatedQuery.fragments(" WHERE ", " AND ");
if (id) {
    where = where.add `CustomerID = ${id}`;
}
if (name) {
    where = where.add `Name like ${name + '%'}`;
}
const q = TemplatedQuery.create `SELECT * FROM Customers ${where}`;

const tq = q.toQuery();
```
Here, If you look in the above example
**_TemplatedQuery.create_** and **_where.add_** are Tagged Templates.

**What will happen if `id` was empty?**  

If `id` was empty, corresponding condition will be skipped and first `AND` will disappear.


**Can you give me the advantage of using the Templated Query?**    
Yes, ofcourse
  
&amp;check; It can prevent SQL Injection attack  
&amp;check; It can combine multiple Template Literals (String literals allowing embedded expressions)

</description>
      <pubDate>Monday, July 26, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/46/Linkedin-Templated-Query.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/Templated-Query-for-TypeScript-1B</guid>
    </item>
    <item>
      <title>Does everyone need a mentor at work? </title>
      <link>https://www.webatoms.in/blog/general/Does-everyone-need-a-mentor-at-work-1A</link>
      <author>Simmi Kava</author>
      <description>###Mentor  
&lt;br/&gt;



I think at some point in our lives we need to stimulate our professional and personal growth. A focused approach, feedback loop, and flexibility are paramount to success. Creating boundaries and sustainability are indispensable to any business.   

Which quote(s) inspired you the most when you were looking for a mentor or adviser, or teacher? 

For me, these are the power quotes:-  

**_"When the student is ready the teacher will appear. When the student is truly ready… The teacher will Disappear._"**  

 _-Tao Te Ching_


**_Tell me and I forget, teach me and I may remember, involve me and I learn.**_  

_-Benjamin Franklin_</description>
      <pubDate>Wednesday, July 21, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/45/mentor-linkedin.png</image>
      <guid>https://www.webatoms.in/blog/general/Does-everyone-need-a-mentor-at-work-1A</guid>
    </item>
    <item>
      <title>Blocking IP Address Using ETERNITY Framework</title>
      <link>https://www.webatoms.in/blog/developer-guide/Blocking-IP-Address-Using-ETERNITY-Framework-19</link>
      <author>Akash Kava</author>
      <description>###How can we block an IP Address using ETERNITY Workflow Framework?  
&lt;br/&gt;

**What is _Eternity_ Workflow Framework?**   

[ETERNITY Framework GitHub Link](https://github.com/neurospeech/eternity) 

**Block IP Address**  


Let's consider a scenario, we want to block the user if they failed to authenticate multiple times in some duration.

Eventually, we end up making tables in the database, and then we have to run a cleanup operation. And sometimes we want to remove IP from the blacklist.

With help of Eternity Workflow Framework, it is very easy to create the same logic, which is durable, available for multiple servers, and does not require creating extra tables/fields. This is because the Eternity framework handles storage automatically.

To create such a workflow, we need to first understand what **_Eternity_** offers.

1. You can initiate a workflow.
2. It stays in execution, and it waits for an external event for a certain duration, otherwise it times out.
3. Workflow is deleted automatically after the execution has finished.

So considering this, let's write small logic:-

1. Before processing the request, check if workflow exists for user IP address with `Result = 'Banned'`.
2. If it exists, then we block it till some time after the last update.
3. If the user fails to authenticate, we create a new workflow `BanUserByIP`, if it does not exist, if it exists, we raise an event as an additional offense.

Inside workflow,
1. We will set `PreseveTimeout` to 5 minutes. 
2. We will wait for an external event for additional offense, and we will increment the counter with a maximum wait time of 1 minute.
3. If the counter is more than 3, we return the workflow with the string "Banned". This will be released after 5 minutes due to `PreserveTimeout` as workflow will be deleted from the storage.

```c#

public class BanUserByIP: Workflow&lt;BanUserByIP, string, string&gt; {

    public const string Offense = nameof(Offense);

    public async Task&lt;string&gt; RunAsync(string ip) {
        PreserveTimeSpan = TimeSpan.FromMinutes(5);
        for(int i = 0; i &lt; 3; i++) {
            var (name,result) = await this.WaitForExternalEvents(
                TimeSpan.FromSeconds(60),
                Offense);
            if(name == Offense) {
                continue;
            }
            // no offense in 60 seconds
            // delete immediately...
            PreserveTimeSpan = TimeSpan.Zero;
            return "NotBanned";
        }
        return "Banned";
    }
}
```

```c#
[HttpGet]
public async Task&lt;IActionResult&gt; LoginPage(
    [FromService] EternityContext context
) {
    var ipAddress = ....
    // azure table storage requires some encoding
    var convertIPAddress = Uri.EscapeDataString(ipAddress);
    var r = await BanUserByIP.GetStatusAsync(context,
        convertIPAddress);
    if(r?.Result == "Banned") {
         return Forbidden();
    }
    ....
}

[HttpPost]
public async Task&lt;IActionResult&gt; LoginPage(
    [FromService] EternityContext context,
    [FromBody] Body model
) {

    if(loginFailed) {
        var ipAddress = ....
        // azure table storage requires some encoding
        var convertIPAddress = Uri.EscapeDataString(ipAddress);
        var r = await BanUserByIP.GetStatusAsync(context,
            convertIPAddress);
        if(r == null) {
            // create a new workflow 
            await BanUserByIP.CreateAsync(context, 
                 convertIPAddress);
        } else {
            // register additional offense
            await context.RaiseEventAsync(
                  convertIPAddress,
                  BanUserByIP.Offense);
        }
     }
     ...
}

```

As you can see, the logic is very well written in **C#**, and the changes in the timeout or modifying logic will not require adding/removing fields from the database.

_**Eternity**_ framework is designed to run on **multiple servers,** the `ban` will span across all the **servers** using same Eternity Storage.

</description>
      <pubDate>Tuesday, July 20, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/44/linkedin-block-ip.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/Blocking-IP-Address-Using-ETERNITY-Framework-19</guid>
    </item>
    <item>
      <title>Embed V8 JavaScript Engine in Xamarin.Android</title>
      <link>https://www.webatoms.in/blog/developer-guide/Embed-V8-JavaScript-Engine-in-Xamarin-Android-18</link>
      <author>Akash Kava</author>
      <description># Isn't there any existing JavaScript engine for Xamarin.Android?  
&lt;br/&gt;

Well, there is **LiquidCore** project, which has Java bindings for V8, you can use it to embed V8 in Xamarin.Android by natively embedding Android Native Project (AAR) files of LiquidCore project.

Also there are other implementations such as **DuckTape**, **JavaScriptCore** etc.

The problem with all of them is, your C# code actually calls (Marshals all parameters) Java code which in turn calls (Marshals all parameters) again to V8.

```text
   // Marshall all parameters 
   CLR Code -&gt; Java Code -&gt; V8 Native

   // Marshal result
   CLR Code &lt;- Java Code &lt;- V8 Native

```

This in turn slows your execution if your code frequently access C# code.

So I decided to remove "Java" bridge to call V8.

# V8 is Embedded as a Native Library

Since V8 is embedded as native library, calls from C# does not go through Java bride.

```text
   CLR Code -&gt; V8 Native
   CLR Code &lt;- V8 Native
```

# V8 Inspector Protocol Support

Currently LiquidCore does not support Inspector protocol, that means you cannot debug your JavaScript. And other libraries such as DuckTape etc does not have any support for debugging at all.

# Xamarin.Android.V8 (`Name is subjected to change in future`)

{% github web-atoms/xamarin-v8 %}

# NuGet Package

NuGet Package is available with ID `Xamarin.Android.V8`

# Inspector Protocol Port

To open Inspector protocol port from your device, you have to click `Visual Studio &gt; Tools &gt; Android &gt; Android Adb Command Prompt`. Then type,
```text
    adb forward tcp:9222 tcp:9222
```

# Create Context

```c#
using(var context = new JSContext( /*Enable Debugging*/ true)) {

  // you can connect to dev tools by visiting url
  // devtools://devtools/bundled/inspector.html?experiments=true&amp;v8only=true&amp;ws=127.0.0.1:9222/backend
  
    context.Evaluate("console.log('I am ready')", "vm");

}
```

Now you have full debugging support in the given link
```text
devtools://devtools/bundled/inspector.html?experiments=true&amp;v8only=true&amp;ws=127.0.0.1:9222/backend
```

# Create New Global Function

Context itself is a global object. So you can store/retrive values on it.

```c#
context["printf"] = context.CreateFunction(0, (c, a) =&gt; {
  // first parameter is context isself
  // second parameter is an array as IJSValue
  System.Diagnostics.Debug.WriteLine(a[0].ToString());
  return c.Undefined;
});

context.Evaluate("  printf('This is from JS Coe'); ", "vm");

// this works as well
context.Evaluate("  global.printf('This is from JS Coe'); ", "vm");
```

# Evaluate Script with Location
```c#
// script location is useful for debugging
context.Evaluate(scriptText, scriptLocation);
```

# Navigate Objects
Each JavaScript object is exposed to CLR as `IJSValue`, you can access properties and methods on this object directly.

```c#
   // Object.create() JavaScript Equivalent in c#
   var obj = context["Object"].InvokeMethod("create");

```

```c#

   var obj = context.CreateObject();
   obj["name"] = context.CreateString("Akash");

   // Object.keys(obj) JavaScript Equivalent in c#
   var keys = context["Object"].InvokeMethod("keys", obj);

   for(var i = 0; i &lt; keys.Length; i++) {
       var key = keys[i].ToString();
       var value = obj[key].ToString();

       //... you have key and value here
   }

```

# Serialize C# Object

When you use method context.Convert method to automatically create native JS values from native types, it will only wrap C# custom object, you cannot call any method or access property from JavaScript on wrapped object. This is done to improve performance. So when you pass C# objects in and out, engine will not create methods and properties on them.

In order to access methods and properties of C# object, you have to serialize them.

```c#
  // you can access all properties, no methods
   var jsDictObject = context.Serialize( customClrObject , SerializationMode.Copy);
   
   // you can access all properties and invoke method as well
   var jsClrObject = context.Serialize( customClrObject , SerializationMode.Reference);
```
&lt;br/&gt;
# Serialization Modes


## Copy

This method will create a deep copy of CLR Object as dictionary which you can easily access inside JavaScript code. This method will fail if there are self referencing objects in the object graph. This limitation may be removed in future, but right now it will throw an exception.

This method is also very slow as deep copy operation will take more time.

Deserialization will also be slow as it will completely construct new object with all properties.

## Reference

Keeps reference along with serialization, every property is serialized as getter/setter, upon deserialization, same object will be returned.

This method is useful for self referencing objects, but this may cause memory leak if you keep reference in JavaScript and JavaScript garbage collector fails to dispose object.

Deserialization is faster as it simply returns referenced object.

## WeakReference

Same as Reference but it only keeps weak reference, you will get object disposed if you try to access object in JavaScript and it is disposed in CLR. CLR is very aggressive while disposing objects, so this may not work if you do not keep reference in CLR. This is also recommended method as it will avoid memory leaks.

## Wrap
This is default serialization method for any object. Object will simply be wrapped and no methods/properties are exposed.  
&lt;br/&gt;

# Thread Safety

This library is not thread safe and it is recommended that you use `JSContext` on the same thread as you created on. Most likely it is better to call in UI Thread.

This is done to avoid unnecessary locking when you don't need them. You can achieve locking in the CLR when you need them.

# License

MIT License

# Big Thanks to

A huge thanks to following GitHub repo to help making this project a reality.

1. [LiquidCore](https://github.com/LiquidPlayer/LiquidCore)
2. [v8-android-buildscripts](https://github.com/Kudo/v8-android-buildscripts)
3. [v8dotnet](https://github.com/rjamesnw/v8dotnet)
</description>
      <pubDate>Friday, July 16, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/43/linkedin-embed-v8-android.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/Embed-V8-JavaScript-Engine-in-Xamarin-Android-18</guid>
    </item>
    <item>
      <title>What and When To Unit Test?</title>
      <link>https://www.webatoms.in/blog/developer-guide/What-and-When-To-Unit-Test-17</link>
      <author>Akash Kava</author>
      <description>###Unit Testing  
&lt;br/&gt;

I have seen many posts about justifying why and why not to unit test, but most posts only talk about burden of writing unit tests, testing framework shortfalls and overhead of mocking in testing.

After writing and deciding not to write unit tests, I have finally compiled one and only one single reason why and what should be unit tested. How is not the question. If you think any testing framework is inadequate, you can simply create one.

So what should be unit tested? 

# Edge Cases


Answer is, "Edge Cases", yes, only the edge cases should at least be unit tested.

## Early Age

Lets take a simple function as an example, we will use C# to demonstrate the reason, however same can be done in any language.

```c#

   int Add(int a, int b) {
      return a + b;
   }

```

Most of you will think that this function will never fail, well hold on, see what will happen when you do `Add(int.MaxValue, int.MaxValue)`.

This is called an edge case.

If you run this code, https://dotnetfiddle.net/H3wmI6

You will see the answer given is `-2`.

Now lets assume that we wrote this simple method and which is used by 10 methods and all 10 methods are used by total of 100 another methods. So you now have 100s of dependent callers to this method.

## Middle Age

At one point, somebody decides that function returning `-2` is really not helpful, so they create a method `VerifyAdd` with following implementation.

```c#
   int VerifyAdd(int a, int b) {
       if( a == int.MaxValue || b == int.MaxValue) {
           throw new ArgumentException();
       }  
       return Add(a, b);
   }
```

And at some part of code we continue to use old `Add` and some part of code we write `VerifyAdd`.

## Mature Age

When project is couple of months old and has entered into maturity, we decide that we should change `Add` method.

```c#
   int Add(int a, int b) {
       if (a == int.MaxValue || b == int.MaxValue) {
            return -1;
       }
       return a + b;
   }
```

Now this is an issue, because half of your logic will expect `ArgumentException` and half of them will expect -1 as return answer. Leading to inconsistency in the logic.

Though this example looks simple, but when code graph is complex, when classes are subclassed and implementations are overriden, inconsistency in code keeps on rising. Now some will come and argue that this is the reason functional programming is best, nope, it is not, same can happen in any language. No language and no framework can ever provide immunity against logical inconsistencies.

# How to identify Edge cases?

1. All exceptions and errors are edge cases. So you must unit test every error, we have to make sure that the callers get correct error messages.
2. Edge cases are also evolved, as we have seen, introducing one change in logic, change introduce new edge case.

# So only edge cases for Unit tests?

Nope, Edge cases are must, arithmetic and time delay related logic must also be unit tested. 

Apart from error edge cases, we must consider logical edge cases 

1. Integer/float overflow
2. Delay, timeout, any method should not indefinitely hang
3. Never eat errors, log them and throw again, Application level unit testing must catch all errors.

# How to learn to write unit tests?

For early developers, it is difficult to understand how and when to write unit tests. Even I was against it and I never wrote in my early years thinking it was total waste of time to unit test `5 == Add(2,3)`, and it is.

To begin with, we should look at how large open source repositories are built and maintained. And look at the simple implementations and simple unit tests backing the logic.

Even if you don't contribute to any open source project, downloading them and browsing them for hours will give you many meaningful insights.</description>
      <pubDate>Wednesday, July 14, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/42/Linkedin-When-and-What-to-Unit-Test-.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/What-and-When-To-Unit-Test-17</guid>
    </item>
    <item>
      <title>CSS: place-items</title>
      <link>https://www.webatoms.in/blog/developer-guide/CSS-place-items-16</link>
      <author>Ajay Singh</author>
      <description>
##### What is a place-items 
&lt;br/&gt;
The **CSS** `place-items` shorthand property allows you to align items along both the block and 
inline directions at once.

Are you working with `Grid` in **CSS** and confused about the content to place center?
Let's understand how can we do this using `align-items` and with `justify-items`.

#### Example 
&lt;br/&gt;
```javascript
&lt;div class="box-1"&gt;
  &lt;div&gt;place-items&lt;/div&gt;
&lt;/div&gt;

.box-1 {
  display: grid;
  justify-items: center;
  align-items: center;
  border: 1px solid red;
  width: 200px;
  height: 200px;
}
```
Let's first understand what these two **CSS** properties does.

**align-items**

 Aligns content along the vertical (column) axis. 

**justify-items**

Aligns along the horizontal (row) axis.


Do you find it difficult to remember the `align-items` `justify-items`.
Here, We have another great **CSS** property called `place-items`.

The `place-items` property in **CSS** is shorthand for the `align-items` and `justify-items` properties,
combining them into a single declaration.
A common usage is doing horizontal and vertical centering with Grid

 Let's rewrite the above example using the single property `place-items`.
&lt;br/&gt;
```javascript
&lt;div class="box-1"&gt;
  &lt;div&gt;place-items&lt;/div&gt;
&lt;/div&gt;


.box-1 {
  display: grid;
  place-items:center;
  border: 1px solid red;
  width: 200px;
  height: 200px;
}
```
No need to remember `align-items` `justify-items`.
The `place-items` property accepts dual values, 
the first for `align-items` and the second for `justify-items`.

#### Another example

if you are working with `justify items` and `align-items` to place the item at the start
like this:-
```javascript
.box-1 {
   display:grid;
   justify-items:start;
   align-items:start.
}
```
#### This is equivalent to:
```javascript
.box-1 {
  display:grid;
  place-items:start;
}
```
If only one value is provided, then it sets both properties.


What makes this property interesting is that it behaves differently based on the context it is used. For example, 
some values only apply to **[Flexbox](https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox)** and will not work in a **[Grid](https://developer.mozilla.org/en-US/docs/Web/CSS/grid)** setting.
Additionally, some values apply to the `align-items` property where others apply to the `justify-items` side.

## [Browser Support](https://caniuse.com/mdn-css_properties_place-items_flex_context)

- Edge 79+ (post-Chromium)
- Firefox 45+
- Chrome 59+
- Safari 11+


#### References

##### **[CSS Box Alignment Model Level 3](https://drafts.csswg.org/css-align-3/#place-items-property "Title")**
The official specification where the place-items property is initially defined.
##### **[Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/CSS/place-items)** 
The Mozilla team’s documentation.
##### **[Box Alignment Cheat Sheet](https://rachelandrew.co.uk/css/cheatsheets/box-alignment)** 
Rachel Andrew’s outline is a super helpful resource for grasping alignment terms and their definitions.


Thank You.
</description>
      <pubDate>Thursday, July 8, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/41/ajay-627.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/CSS-place-items-16</guid>
    </item>
    <item>
      <title>Why JS Array Methods support array-like objects?</title>
      <link>https://www.webatoms.in/blog/developer-guide/Why-JS-Array-Methods-support-array-like-objects-15</link>
      <author>Simmi Kava</author>
      <description>###JavaScript: Array-like Objects  
&lt;br/&gt;

**What is an array-like object?** 

When any object look and behave like arrays on the surface but do not share all of their methods is called `array-like object`. Such objects have length property and members are stored at numeric index. You cannot call array methods directly on `array-like` objects but you can call them indirectly using `Function.prototype.call()`. 

**Why JS Array methods support Array-like Objects?** 

So that you can easily expose some native implementation with length property and numeric index `(uint32)` which can act like an array. 


**Can you name few such objects which are native to JavaScript?**

Certainly.

**1. Arguments Object:** 

The arguments object made available within the body of function is an `array-like` object. But can we call the `forEach()` method on `arguments` object? No, it does not implement the `forEach()` method. Similarly, the methods `pop()`, `shift()`, and `slice` cannot be directly called on arguments object, you can do it through `Array.prototype.call`.

[Click here to view the JavaScript MDN Example: ](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections)

Another Example:

```javascript
function webAtoms() {
console.log("Hello, I am MVVM framework for JS." + 
	     " Do you know my length?" + 
	     "It is: " + arguments.length);
console.log("Property Names:" , Object.getOwnPropertyNames(arguments));
console.log("Keys:" , Object.keys(arguments));
}

webAtoms("Web", "Atoms");
```
**_Output:_**  

```javascript
Hello, I am MVVM framework for JS. Do you know my length? It is: 2
Property Names: (4) ["0", "1", "length", "callee"]
                            0: "0"
                            1: "1"
                            2: "length"
                            3: "callee"
                            length: 4
                            __proto__: Array(0)
Keys: (2)["0", "1"]
         0: "0"
         1: "1"
         length: 2
         __proto__: Array(0)

```
If you look at the example above. The `arguments` object has non-enumerable property `length` and hidden key `callee` (some environments display `caller` as one of the properties too). How can we confirm that `length` property is non-enumerable? 

We know that the `Object.keys()` method returns an array of an object's own enumerable property names, iterated in the same order that a normal loop would.

When we try to log the `Object.keys(arguments)`, it yields only `"0"` and `"1"` as the keys and doesn't list `length` as the key.

The key `callee` contains the instance-of function in non-strict mode. You can always try printing the same inside the function. 
```javascript
console.log(arguments.callee)
```
If you try to access it in the strict-mode, it results into `TypeError`. 

**2. document.getElementsByTagName() and document.getElementsById()**   
HTML DOM has many array-like objects. 


**3. JavaScript TypedArrays**   
JavaScript TypedArrays are array-like objects and provide a mechanism to access the raw binary data. 

Hope this article was informative. </description>
      <pubDate>Monday, July 5, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/37/Linkedin-array-like-objects.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/Why-JS-Array-Methods-support-array-like-objects-15</guid>
    </item>
    <item>
      <title>Developer Myths</title>
      <link>https://www.webatoms.in/blog/general/Developer-Myths-14</link>
      <author>Simmi Kava</author>
      <description>### How does an outsider usually perceive a Developer or a Programmer?


It is common for people to perceive a technical programmer or developer as a an all-rounder who is also computer Hardware Specialist, a technical support engineer a video game programmer, a person who can convert any and every requirement into an automated solution. 

So, as a programmer this is how I can code "US"! Look into the image associated with the post :-)

Have you come across such people? Comments are welcome!

</description>
      <pubDate>Friday, July 2, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/36/2july-LINKEDIN-DEVELOPER-MYTHS.png</image>
      <guid>https://www.webatoms.in/blog/general/Developer-Myths-14</guid>
    </item>
    <item>
      <title>JavaScript: White Space &amp; Line Terminator Code Points (Unicode)</title>
      <link>https://www.webatoms.in/blog/developer-guide/JavaScript-White-Space-Line-Terminator-Code-Points-Unicode-13</link>
      <author>Simmi Kava</author>
      <description>###JavaScript:  Unicode Support in JavaScript
&lt;br/&gt;

**What are White Space and Line Terminators?**

White Space and Line Terminators code points are used to improve the readability of source code and to separate indivisible lexical units (tokens) from each other. Line terminators influence the syntactic grammar and process of semicolon insertion. 

The below source code explains some of the permitted `Unicode` and what happens when we use `trim()` function on these Unicode's.

```javascript
'\tHi WebAtoms\t'.trim(); // &lt;TAB&gt; Or \u0009 - Character Tabulation
'\u000BHi WebAtoms\u000B'.trim(); //&lt;VT&gt; Line Tabulation -Vertical Tab
'\u000CHi WebAtoms\u000C'.trim(); // &lt;FF&gt; Form Feed or '\f'
'\u00A0Hi WebAtoms\u00A0'.trim(); //&lt;NBSP&gt; - No-Break Space
'\uFEFFHi WebAtoms\uFEFF'.trim(); //&lt;ZWNBSP&gt; - Zero Width No Break Space
'\rHi WebAtoms\r'.trim(); //&lt;CR&gt; Carriage Return or \u000D
'\nHi WebAtoms\n'.trim(); //&lt;LF&gt; - Line Feed or \u000A
'\u2028Hi WebAtoms\u2028'.trim(); //&lt;LS&gt; - Line Separator 
'\u2029Hi WebAtoms\u2029'.trim(); //&lt;PS&gt; - Paragraph Separator 
'\u2001Hi WebAtoms\u2001'.trim(); //Em Quad alias Mutton Quad
```
For more details on White Space and Line Terminator, visit the ECMA Script link:-

ECMA Script: [ECMA Script Reference] (https://tc39.es/ecma262/#sec-white-space)

The unicode `u2001` belongs to the `Other Category "Zs"`.  When I stumbled upon the unicode support in Javascript, I landed on this blogpost, which also explains other functions and `"Zs"` category unicode.

Blog Post: [Unicode Support In JavaScript](http://roysharon.com/blog/44)

Another reference: [JavaScript Character Escape Sequences](https://mathiasbynens.be/notes/javascript-escapes)

Hope these resources are helpful. Happy Learning!

</description>
      <pubDate>Thursday, July 1, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/35/WhiteSpace.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JavaScript-White-Space-Line-Terminator-Code-Points-Unicode-13</guid>
    </item>
    <item>
      <title>JavaScript: break in labeled blocks</title>
      <link>https://www.webatoms.in/blog/developer-guide/JavaScript-break-in-labeled-blocks-12</link>
      <author>Simmi Kava</author>
      <description>###'BREAK' Statement in 'labeled' blocks.  
&lt;br/&gt;

We have used `break` statement in `while` loop, `for` loop and `switch` statements. But we can also use `break` statement within a labeled block. Let's take a look at the example:-

What would be the output of the below code snippet? 
```javascript
{
   var a = 1;
   named: {
      a++;
      break named;
      a++;
   } 
   console.log(a);
}
```

**_Output:_**

```javascript
2
```

A `break` statement should be nested in the referenced label. Here 'named' is the label and `break &lt;label-name&gt;` is the syntax used to break or bypass the logic in the labeled block `named`. 

Can we use it like the `GOTO` statement in the labeled blocks? **No**.  `Break` and `Continue` can be used in the loops to give you the civilized form of `GOTO` statement. Let's look at the example


What would be the output of the below code snippet? 
```javascript
label1: {
console.log("I am in Label 1");
break label2:
}

label2: {
console.log("I am Label 2");
}
```

**_Output:_**

```javascript
SyntaxError: Undefined label 'label2'
```
So, as we can see in the above example, we cannot jump or goto `label2` from `label1` using `break`.

Can I use `continue` in the `labeled` blocks? **NO**. Let's us evaluate the same example and replace `break` with `continue`.

```javascript
{
   var a = 1;
   named: {
      a++;
      continue named; //break replaced with `continue`
      a++;
   } 
   console.log(a);
}
```

**_Output:_**
```javascript
SyntaxError: Illegal continue statement: 'named' does not denote an iteration statement
```

Can we have `nested` labeled blocks? **Yes**, we can.

```javascript
firstLabel: {
secondLabel: {
console.log("Hi WebAtoms");
break firstLabel;
console.log("Will you print me?");
}
console.log("Am I in scope?");
}
```
**_Output:_**
```javascript
Hi WebAtoms
```
If you look at the snippet, it breaks out of both `firstLabel` and `secondLabel`. If I replace the `break` statement as shown below:-

```javascript
firstLabel: {
secondLabel: {
console.log("Hi WebAtoms");
break secondLabel;
console.log("Will you print me?");
}
console.log("Am I in scope?");
}
```

**_Output:_**
```javascript
Hi WebAtoms
Am I in scope?
```  
Can I use `break` within functions nested in a loop or labeled block?
**NO**, If we try to use `break` statement within functions that are nested in a loop or labeled block, it will generate `SyntaxError`. Which also implies, `labeled blocks` cannot contain `functions`.


[MDN Reference Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break)

Hope you have learnt something new today. Happy learning. 
</description>
      <pubDate>Monday, June 28, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/34/JavaScript-break-in-labeled-blocks.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JavaScript-break-in-labeled-blocks-12</guid>
    </item>
    <item>
      <title>ETERNITY Workflow Framework</title>
      <link>https://www.webatoms.in/blog/general/ETERNITY-Workflow-Framework-11</link>
      <author>Simmi Kava</author>
      <description>###ETERNITY WORKFLOW FRAMEWORK for .NET

Long running workflows with ability to suspend and replay the workflow in future.


**_Features_:-**

- Strongly Typed API
- Dependency Injection
- Activities are C# Methods
- Wait for External Event
- Really very very large workflows
- Exception Handling
- Exception with Filter
- Recursive Activities or Nested Activities Not Supported
- Azure Table storage and Blob storage
- `NeuroSpeech.Eternity.Mocks` package provides with Mock Engine and storage for Unit Testing. 
- Sqlite Storage for Mobile 

**[Click here to access the GitHub Repository](https://github.com/neurospeech/eternity)**</description>
      <pubDate>Thursday, June 24, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/33/Eternity-Framework-NS.png</image>
      <guid>https://www.webatoms.in/blog/general/ETERNITY-Workflow-Framework-11</guid>
    </item>
    <item>
      <title>JavaScript: Property Shadowing &amp; Enumeration</title>
      <link>https://www.webatoms.in/blog/developer-guide/JavaScript-Property-Shadowing-Enumeration-10</link>
      <author>Simmi Kava</author>
      <description>###Property Shadowing &amp; Enumeration  
&lt;br/&gt;

**What is Prototype?**

JavaScript objects inherits features (`methods` and `properties`) from one another through a mechanism named `Prototype`.

**What is Prototype Chain?**

An object's prototype may further have a prototype object, from which it inherits methods and properties (so on and so forth). This is referred to as `prototype chain`. When trying to access a property of an object, JavaScript will first search for the property on the object, followed by the object’s prototype, followed by the object’s prototype prototype and so on till it find the property or till the end of prototype chain i.e. `null`. 

**What is Property Shadowing?**

When you are creating a property on an object which has the same property name as on its prototype chain, it will not be evaluated and enumerated i.e. properties with same name are shadowed and therefore will not be enumerated. This implies that `property` defined on `object` is evaluated first before looking into its prototype property. 


```javascript
output = []; 
for (var x in Object.create(
	{a:10, b:20, c:30}, {a:{value:40}, 
	b:{value:50, enumerable:true}})) 
output.push(x) ;
console.log(output.toString());
```
**_Output:_**

```javascript
b,c
```

**_Explanation:_**
1. All properties in the prototype chain should be enumerated, but the same property       name is never enumerated twice.  
2. Properties in the prototype chain with the same name are shadowed and therefore are not enumerated.
3. Here, `a` is `enumerable:false` in it's `prototype`, hence is not enumerated.

**_Syntax_**

```javascript
Object.create(proto)
Object.create(proto, propertiesObject)
```
Let's store the Object in a variable `x1`
```javascript
var x1 = Object.create(
    {a:10, b:20, c:30}, {a:{value:40}, 
    b:{value:50, enumerable:true}})
```
Now, lets print `x1`. It contains the following - `prototype` and `propertiesObject`

```javascript
x1

{b: 50, a: 40}    
  b: 50
  a: 40

__proto__:    
  a: 10
  b: 20
  c: 30
  __proto__: Object
```
The `Object.keys()` method returns an array of a given object's own enumerable property names. So as we see here, `a` is not enumerable. 

```javascript
Object.keys(x1)
["b"]
```
But, if we try to evaluate `x1.b` it is not `undefined`
```javascript
x1.b
50
```
The `Object.getOwnPropertyNames()` method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.

Let's check the output
```javascript
Object.getOwnPropertyNames(x1)
(2)["a", "b"]
```
The `Object.getOwnPropertyDescriptors()` method returns all own property descriptors of a given object.

```javascript
Object.getOwnPropertyDescriptors(x1)
{a: {…}, b: {…}}
  a: {value: 40, writable: false, enumerable: false, configurable: false}
  b: {value: 50, writable: false, enumerable: true, configurable: false}
  __proto__: Object
```
If we look in the above output, `a` is `enumerable: false`. But `b` is `true` as we have manually set it to `true`.
 
```javascript
Object.getOwnPropertyDescriptors(x1.__proto__)
{a: {…}, b: {…}, c: {…}}
  a: {value: 10, writable: true, enumerable: true, configurable: true}
  b: {value: 20, writable: true, enumerable: true, configurable: true}
  c: {value: 30, writable: true, enumerable: true, configurable: true}
  __proto__: Object
```
If we look in the above output `c` is enumerable: true. Hence `c` is printed in the output.

Hence, finally in the output `b` and `c` are enumerated and we get `b,c` as the output. Hope this explains the concept in detail.

Happy Learning!</description>
      <pubDate>Monday, June 21, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/32/linkedin-javascript-prototype-shadowing.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JavaScript-Property-Shadowing-Enumeration-10</guid>
    </item>
    <item>
      <title>JavaScript: Return Statement Behavior</title>
      <link>https://www.webatoms.in/blog/developer-guide/JavaScript-Return-Statement-Behavior-Z</link>
      <author>Simmi Kava</author>
      <description>###Return Atypical Behavior  
&lt;br/&gt;

What would be the output of below JavaScript code and why?

_Example 1_
```javascript
Array.from([3, 4], 
function (value, index) { 
return value + 1; 
}).toString()
```
**Output:**
```javascript
"4,5"
```

_Example 2_
```javascript
Array.from([3, 4], 
function (value, index) { 
return
value + 1;
 }).toString()
```

**Output:**
```javascript
","
```

Surprised? Go back to the code example and revisit how the `return` statement is placed in each of the above example.

The `return` statement and the `expression` must be placed in the same line.

Example 1 `return` statement is written as:
```javascript
return value + 1; 
```

Example 2 `return` statement is written as:
```javascript
return
value + 1;
```

In the Example 2, a Semicolon is a automatically inserted after the `return` statement. Hence, anything after the return statement has no impact on the logic  and since the expression is ignored, the return value is `undefined` and when we call toString() on `undefined`, it returns empty value and index. 

Visit [ECMAScript: The return Statement] (https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-return-statement) link to learn more.</description>
      <pubDate>Thursday, June 17, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/31/linkedin-J-A-V-A-S-C-R-I-P-T-return.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JavaScript-Return-Statement-Behavior-Z</guid>
    </item>
    <item>
      <title>JavaScript: Optional Chaining Operator (?.)</title>
      <link>https://www.webatoms.in/blog/developer-guide/JavaScript-Optional-Chaining-Operator-Y</link>
      <author>Simmi Kava</author>
      <description>###Optional Chaining  Operator (?.)  
&lt;br/&gt;


This operator allows you to read the value of property situated deep within a chain of connected objected without the need to check if each reference in the chain is valid or not. 

**Difference between `?.` and `.` chaining operator**

`.` chaining operator throws an `error` if a reference is null or undefined.

`?.` will return `undefined` if a reference is null or undefined. 

The optional chaining operator comes handy when you are evaluating an object and unsure which all properties of the object are required. 

**Can we use `?.` on `undefined` root object?**

Yes

**Can we use `?.` on root object which is not declared?**

No

**_Syntax_**

obj.val?.prop

obj.val?.[expr]

obj.arr?.[index]

obj.func?.(args)

**_Examples_**

```javascript
const i = undefined;
const j = {val: 0};
const c = {};
c[undefined] = 11;
const k = [22];


console.log(i?.[i?.j]); //undefined
console.log(c?.[i?.j]); //11
console.log(k?.[j?.val]); //22
```

**Optional Chaining - Method Call Example**

```javascript
var a = {};

var b = 1;

function add() {
    b++;
    return b;
}

console.log(a?.method?.(add())); //undefined 
console.log(b); //1

console.log(a.method?.(add())); //undefined
console.log(b); //1

```



**Optional Chaining Index Example**

```javascript
var a = null;

var b = 1;

function add() {
    b++;
    return b;
}
var n = a?.[add()];
console.log(n); //undefined
console.log(b); //1
```

Keep Learning!



</description>
      <pubDate>Tuesday, June 15, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/30/Linkedin-Optional-Chaining--.-.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JavaScript-Optional-Chaining-Operator-Y</guid>
    </item>
    <item>
      <title>JavaScript: Trailing (Final) Commas - Facts</title>
      <link>https://www.webatoms.in/blog/developer-guide/JavaScript-Trailing-Final-Commas-Facts-X</link>
      <author>Simmi Kava</author>
      <description>###Did you know the following JS Trailing Comma Facts ?
&lt;br/&gt;

- **In Arrays, trailing commas are ignored. More than 1 comma if used, produces an elision or hole**

```javascript
var array = [10,20,30,];
console.log(array); //[10,20,30]
console.log(array.length) //3
```

But if,

```javascript
var array = [10,20,30,,,,];
console.log(array); //[10,20,30,,,] -&gt; empty * 3
console.log(array.length) //6
```

An array with holes is called as sparse array. When iterating array (using `forEach()` or `map()`), holes are skipped

- **Function / Method parameter definitions or invocation, trailing commas are legal**

```javascript
function funWithJS(arg) {}
function funWithJS(arg,) {}
```

Or,
```javascript
(arg) =&gt; {}
(arg,) =&gt; {}
```

are valid function calls.

Similarly,

```javascript
class Shape{
circleArea(radius,) {return 3.14 * radius}
rectangleArea(length,width,){return length * width}
} var obj = new Shape();

console.log(obj.circleArea(5)); // 15.700000000000001
console.log(obj.rectangleArea(5,10)); //50

```
When invoked with trailing comma, also yields the same result.

```javascript
console.log(obj.circleArea(5,)); // 15.700000000000001
console.log(obj.rectangleArea(5,10,)); //50
```

**_Note: -_** Function or Method invocation or definition containing only a comma wil throw a `SyntaxError`.

- **Trailing commas in Destructuring assignment* or object literals is legal**

```javascript
var user = {
name: "WebAtoms",
type: "Framework",
};
```
A trailing comma is allowed on the left-hand side when using destructuring assignment. 

```javascript
// array destructuring with trailing comma
[i, j,] = [10, 20];

// object destructuring with trailing comma
var user = {
  id: 100,
  active: true,
};
var {id, active,} = user;
```

**_Note: -_** Trailing comma when used with a rest element, will give a `SyntaxError`. Also, `JSON` doesn't allow trailing commas. 

```javascript
var [a,...b,] =  [1,2,3]; //SyntaxError
```


Happy Learning! </description>
      <pubDate>Thursday, June 10, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/28/linkedin-trailing-commas-10june.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JavaScript-Trailing-Final-Commas-Facts-X</guid>
    </item>
    <item>
      <title>C# - Aggressive Inlining</title>
      <link>https://www.webatoms.in/blog/developer-guide/C-Aggressive-Inlining-W</link>
      <author>Simmi Kava</author>
      <description>###Aggressive Inlining - When it doesn't work ?  
&lt;br/&gt;

**What is Inlining?**

A process in which code is copied from one function directly in to the body of the another function (i.e. to the function which uses the code from the called function).

**What are it's advantages?**

- Stack is reduced i.e. variables need not be push and pop from the stack. 
- Context specific optimization on the body of function is feasible.
- No function call or return call overhead needs to be maintained.


**What is Aggressive Inlining?**

JIT (Just In Time) compiler can logically determine which methods can be inlined. But at times, we know logic better than the compiler. Isn't it? So how do we force JIT compiler to perform the inlining? The answer is "**_Aggressive Inlining_**",

**_Syntax:_**

`[MethodImpl(MethodImplOptions.AggressiveInlining)]`

static int MethodName() {
}

**Name the scenarios, where Aggressive Inlining won't work?**
- _MarshalByRef_ : Since calls have to intercepted, executed and dispatched, MarshalByRef classes cannot be inlined.

- _Virtual Calls_ : Since the end target of the call is unknown, this is ignored.

- _Valuetypes_ : When `valuetypes` are passed as reference or when `valuetypes` are copied by compiler to avoid unexpected mutation.

- _Virtual Machine(VM) Restrictions_ : JIT needs to seek permission from the VM to inline a method e.g. like in `iOS` this is just not possible as platform doesn't allow it. 

- _Complex Flowgraph_ : This includes complex loops or exception handling (try-catch) and similar scenarios. 

Besides this, any security probe or non-native IL instructions are also out of scope of inlining. 

Hope you learnt something new today. Happy Monday!




- </description>
      <pubDate>Monday, June 7, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/27/linkedin-csharp-aggressive-inlining.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/C-Aggressive-Inlining-W</guid>
    </item>
    <item>
      <title>JavaScript: Object.freeze() -yields "true"</title>
      <link>https://www.webatoms.in/blog/developer-guide/JavaScript-Object-freeze-yields-true-R</link>
      <author>Simmi Kava</author>
      <description>###Object.freeze()  
&lt;br/&gt;

As we already know, Object.freeze() method freezes an object which means, object can no longer be changed, no new properties can be added, existing properties and their values cannot be modified.

In one of our previous blog, we had already explained the CRUD operations on Object.freeze(), Object.seal() and Object.preventExtensions() method. Here is the quick reference.

[CRUD Operations - Object - freeze() | seal() | preventExtensions()](https://www.webatoms.in/blog//developer-guide/CRUD-Operations-Object-freeze-seal-preventExtensions-J)

```javascript
Object.freeze(100) === 100 //true
 
Object.freeze(null) === null //true

Object.freeze() === undefined //true

Object.freeze(undefined) === undefined //true
```

If we see in the above example, if the argument is not an `object` i.e. is `number`, `null` or `undefined`, `Object.freeze()` has no impact and does not do anything and always the result of `strict comparison` is `true`.

Same goes with ` Object.preventExtensions()`. Let's see the example below:-

```javascript
Object.preventExtensions(100) === 100 //true
 
Object.preventExtensions(null) === null //true

Object.preventExtensions() === undefined //true

Object.preventExtensions(undefined) === undefined //true
```


</description>
      <pubDate>Wednesday, June 2, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/26/linkedin-Object.freeze---behvaior.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JavaScript-Object-freeze-yields-true-R</guid>
    </item>
    <item>
      <title>JavaScript: Tail Call Optimization</title>
      <link>https://www.webatoms.in/blog/developer-guide/JavaScript-Tail-Call-Optimization-Q</link>
      <author>Simmi Kava</author>
      <description>###Tail Call Optimization

ECMAScript 6 offers `tail call optimization`, but many engines do not support or provide this.

**When do we say a function qualifies for `tail call optimization`?**

If the last statement in a function body is `return` statement which contains single function call, qualifies for the tail call optimization. Why does the engine optimize it? The answer is to reduce the `call stack`.

**How does this optimization help?**

You get more stack to work with, execution is comparatively fast and allows you to execute more number of iterations before the stack overflow error occurs.

Let's learn how to write a Fibonacci Sequence example in JavaScript with and without the `tail call optimization`.

**Fibonacci Sequence**

The Fibonacci numbers, commonly denoted `Fn`, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1.

**_Without Tail Call Optimization_**
```javascript
function fibonacci(input)
    {   
        if(input &lt;= 1)
            return input;
        return fibonacci(input - 1) + fibonacci(input - 2);
    }


var num = 10;
console.log(`fibonacci(${num}) =  ${fibonacci(num)}`);
```

**_With Tail Call Optimization_**
```javascript
function fibonacci(input, x = 0, y = 1)
{
    if (input == 0){
        return x;
    }
    if (input == 1){
        return y;
    }

    return fibonacci(input - 1, y, x + y);
}
 

var num = 10;
console.log(`fibonacci(${num}) =  ${fibonacci(num)}`);
```

**_Output_ (for both the logic):-**
```javascript
fibonacci(10) =  55
```
</description>
      <pubDate>Monday, May 31, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/25/Linkedin-JavaScript-Tail-Call-Optimization---Fibonacci-Series.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JavaScript-Tail-Call-Optimization-Q</guid>
    </item>
    <item>
      <title>JavaScript: Array Loose Equality - Behavior</title>
      <link>https://www.webatoms.in/blog/developer-guide/JavaScript-Array-Loose-Equality-Behavior-P</link>
      <author>Simmi Kava</author>
      <description>### Array Loose Equality Strange Behavior

Loose equality compares the two values after converting both the values to a common type. After conversion, both or one side may undergo conversion and final comparison is performed as `Strict Equality`


Why most the above expressions yield `true` or `false` is explained in the ECMA Script [Abstract Equality Comparison Rules](https://262.ecma-international.org/11.0/#sec-abstract-equality-comparison).


</description>
      <pubDate>Friday, May 28, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/24/array-equality.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JavaScript-Array-Loose-Equality-Behavior-P</guid>
    </item>
    <item>
      <title>JavaScript: Class - Facts</title>
      <link>https://www.webatoms.in/blog/developer-guide/JavaScript-Class-Facts-N</link>
      <author>Simmi Kava</author>
      <description>###Classes

Classes are template for creating objects. They are "special functions" and have two components:

- Class Expression
- Class Declaration

Let's learn about some facts related to a Class.

**1. Class declarations are not hoisted**

Function declarations are hoisted but class declarations are not. The class has to be declared first and accessed later, otherwise will throw a `Reference Error`.

```javascript
var shape = new Shape(); //Reference Error 

class Shape{}
```
**2. Class body always 'use strict' syntax**

All the code written in a `class` construct is subject to `strict mode` syntax for increased performance.

**3. Class can be used as an expression**

Class expressions may or may not have a binding identifier. They allow you to redfine classes without errors. The `typeof` classes generated using class expression always returns `function`. The classes can be defined inside another expression, passed, returned or assigned; when used as a class expression.

**4. Class methods are non-enumerable**

Once you define a class, the `enumerable` flag is set to `false` for all methods in the `prototype`. This helps when we execute `for...in` over an object, class methods are usually not needed. 


**5. Classes can be created dynamically i.e. at runtime**

```javascript
function webAtoms(input) {
return class {
greet() {
console.log("Hello " + input); 
}
};
}

var message = webAtoms("WebAtoms"); //Create a new class
new message().greet(); //Hello WebAtoms
```

**6. 'Class fields' allows to add data property to a class**

Class fields synatx allows to add any data property to a class. The property created using `class fields` is not set on on class `prototype`, but on the individual object.

```javascript
class Software{
name = "WebAtoms";
type = "FrameWork"
}

var software = new Software();
console.log("Hello " + software.name + " " + software.type); //Hello WebAtoms Framework
console.log("Software Prototype: ", Software.prototype.name) //undefined
```

**_Output_**

```javascript
Hello WebAtoms FrameWork
Software Prototype:  undefined
```

We can also use complex expression and function calls for a class field. 

**7. Class may include getter/setter or compound properties**

The syntax is similar to object literals. 

```javascript
class GetSetDemo {
get data() {
return "I am getter property";
}
set data(message) {
console.log(message + " I am a setter property")
}

}

var getSetDemo = new GetSetDemo();
getSetDemo.data = "Hi,";
console.log(getSetDemo.data);
```

**_Output_**
```javascript
Hi, I am a setter property
I am getter property
```

**8. Class expression identifier is visible only to class**

The identifier i.e. name with which a class expression is identified is visible within the expression only. You cannot access it from the outside. 


```javascript
const Demo = class Test{
getIdentifier() {
return Test.name;
}
};

var instance = new Demo();
console.log(instance.getIdentifier()); //Test
console.log(Test.name); //Reference Error
```

**_Output_**

```javascript
Test
Uncaught ReferenceError: Test is not defined
```

**9. Base Class can be provided dynamically**

Like, you can create classes at run-time; base class can also be provided at run-time. 



**Final Notes**
- `eval` or `arguments` are reserved keywords and cannot be used as `class` names
- `constructor` name cannot be used for a generator method or getter/setter method 
- `prototype` methods cannot be used as constructor; results in `TypeError`


</description>
      <pubDate>Monday, May 24, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/23/Linkedin-JavaScript-Classes.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JavaScript-Class-Facts-N</guid>
    </item>
    <item>
      <title>JavaScript: Sequence Expression - The Comma Operator (,)</title>
      <link>https://www.webatoms.in/blog/developer-guide/JavaScript-Sequence-Expression-The-Comma-Operator-M</link>
      <author>Simmi Kava</author>
      <description>###Comma Operator(,)  
&lt;br/&gt;

Is the comma operator same as comma within arrays, objects, and function parameters and arguments?

**NO!** It is completely different from them. Comma operator is expression separator where as semicolon (;) is a statement separator.

This operator evaluates each operand value from left to right and returns the last operand. As shown in the example, when we execute the `valueOf()` method on the `Object`, it returns the value as `30` i.e. last value of the operand. 

_**Syntax**_ 

expr1, expr2, expr3...


**What is it's use?**

If you want to supply multiple parameters in a `for` loop, this can be handy. It also allows you to use multiple expressions in a place where one expression is expected. Examples:

- `array` swapping without using a temporary variable. 
- `console.log` statements
- Arrow (lamda) function 
- Array `reduce()` method

[Examples](https://stackoverflow.com/questions/9579546/when-is-the-comma-operator-useful)

**Runtime Algorithm:**

1. Evaluate expression (exp)
2. Perform ?GetValue(exp)
3. Evaluate Assignment Expression (res)
4. Return ?GetValue(res)

[Ref: ECMAScript Comma Operator](https://tc39.es/ecma262/#sec-comma-operator)

`GetValue()` must be called irrespective of the value being used or not; as it may have observable side-effects.

Note that, [Operator precedence and associativity](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) rules are applied to determine how operators are parsed.


Happy Learning!



</description>
      <pubDate>Wednesday, May 19, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/22/Linkedin-Sequence-Expression-Comma-Operator.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JavaScript-Sequence-Expression-The-Comma-Operator-M</guid>
    </item>
    <item>
      <title>C#: 'is' Operator - An expensive operation</title>
      <link>https://www.webatoms.in/blog/developer-guide/C-is-Operator-is-an-expensive-operation-K</link>
      <author>Akash Kava</author>
      <description>### Switch Pattern Matching for Types can be costly!

Pattern matching is great, makes life easier, but it comes with a cost. Most of the time the cost is negligible. But it is better to know when not to use it.

Lets assume following simple case,

# Pattern Matching

```c#
    public abstract class Shape {
    }
    
    public class Circle: Shape {
        public double Radius;
    }
    
    public class Rectangle: Shape {
        public double Width;
        public double Height;
    }
```

We want to calculate area, by using pattern matching, so here is the code.

```c#
    public double Pattern(Shape shape) {
        switch(shape) {
            case Circle circle:
                return Math.PI * circle.Radius * circle.Radius;
            case Rectangle rectangle:
                return rectangle.Width * rectangle.Height;
        }
        throw new NotSupportedException();
    }
```

Now lets analyze JIT ASM generated for above code,

```asm
C.Pattern(Shape)
    L0000: push rsi
    L0001: sub rsp, 0x20
    L0005: vzeroupper
    L0008: mov rsi, rdx
    L000b: mov rdx, rsi
    L000e: mov rcx, 0x7ffb9945d250
    L0018: call 0x00007ffbef626620
    L001d: test rax, rax
    L0020: jne short L0049
    L0022: mov rdx, rsi
    L0025: mov rcx, 0x7ffb9945d3c0
    L002f: call 0x00007ffbef626620
    L0034: test rax, rax
    L0037: je short L0064
    L0039: vmovsd xmm0, [rax+8]
    L003e: vmulsd xmm0, xmm0, [rax+0x10]
    L0043: add rsp, 0x20
    L0047: pop rsi
    L0048: ret
    L0049: vmovsd xmm0, [rax+8]
    L004e: vmovaps xmm1, xmm0
    L0052: vmulsd xmm1, xmm1, [C.Pattern(Shape)]
    L005a: vmulsd xmm0, xmm0, xmm1
    L005e: add rsp, 0x20
    L0062: pop rsi
    L0063: ret
    L0064: mov rcx, 0x7ffb8fbddfd8
    L006e: call 0x00007ffbef6278f0
    L0073: mov rsi, rax
    L0076: mov rcx, rsi
    L0079: call System.NotSupportedException..ctor()
    L007e: mov rcx, rsi
    L0081: call 0x00007ffbef5eb3a0
    L0086: int3
```

Notice lines,  `L0018: call 0x00007ffbef626620` and `L002f: call 0x00007ffbef626620`, both calls are to check whether the object is of instance requested. I was also surprised to see this as pattern matching can also match an interface/base class. So it is not simple comparison. Every pattern matching case requires separate `CALL` instruction, which is a considerable overhead on CPU.

So, in simple words, the last case will always require all `instance of` `CALL` before hitting the case. You can certainly move the most used cases on the top to make life easier.

# Plain old OOPS

```c#
    public abstract class Shape {
        public abstract double Area();
    }
    
    public class Circle: Shape {
        public double Radius;

        public override double Area()
        {
            return Math.PI * Radius * Radius;
        }
    }
    
    public class Rectangle: Shape {
        public double Width;
        public double Height;
        
        public override double Area() {
            return Width * Height;
        }
    }
```

Now lets call `Area` method and see what JIT ASM generates.

```c#
    public double Area(Shape shape) {
        return shape.Area();
    }
```

```asm
C.Area(Shape)
    L0000: mov rcx, rdx
    L0003: mov rax, [rdx]
    L0006: mov rax, [rax+0x40]
    L000a: mov rax, [rax+0x20]
    L000e: jmp rax
```

It is simplest single call, it loads and address and jumps to it and returns from the method. The speed is achieved by avoiding instance of checks.

# Complete sample

[Sample Program Link](https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA0AXEBDAzgWwB8ABAJgEYBYAKGIGYACMhgYQYG8aHunHiUGAWQAUASg5ceAX0ndZvBgBMIAV2AAbGAwCCsbMIDKAC2wAHLbhPnxnaj3tMA7A0tmYAOl0x9ogNzyZOx55eiVVDS0ABWwMDBgoADtDKwsUm3l7XAB3AEsMMCNhV2sJIIcHMDwtFhyoME0GMFr6mBAM8odiZ0EYo3dIgEkGACpG5s13ACVsRRyVXBGxuonp2fn/Mo7uStwtSZgwDGwEgHMG2EPjs9b2re4uhguj04mAdRzFDCNFp6uJgAkYDkTkYMBstoEtl8oBAsgwEjA4QA5CAYAwqUymaBxRQAUQQYBgpgwOQgST8AXkIUY2GAuAwUGwhyYpAYxjcpS2oVp9MZzOUagaXh84OkVM2oWYNWWrTZKU5HVCAoiDFWc1wG1uCggADd4lAPlplUK9GItbY7jwHj0vv0hqM1fNFo6NVrIWLNtSWaqDs9riA5RyLYrGMatO9PkZReUleEGoDgaDow4taFdfrDWFBVphWIFZaHhGvosEyCwW7KdQpEA=)

# Can performance of Pattern matching improved?

Not really, high level languages usually store too much type information in order to provide improved pattern matching. But underlying cost of every single comparison is costly.

In Processor, any type of processor, be it ARM, X64 or any, single numeric comparison is much caster than hierarchical or sequential types. Basically type matching is a multi step comparison.

This is also the reason V8 team decided to store Enum flag to detect type in JavaScript inbuilt type instead of pattern matching.

# Conclusion 
Checking `instance of` `&lt;class&gt;` is expensive operation in any programming language as it needs to check for inheritance.

# Branchless

OOPS will also make most of your code branchless, which makes CPU eagerly load next set of instruction to execute instead of missing branch cache and slowing the execution.

More about branchless coding

{% youtube bVJ-mWWL7cE %}


</description>
      <pubDate>Tuesday, May 18, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/21/linkedin--is--operator-An-expensive-operation.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/C-is-Operator-is-an-expensive-operation-K</guid>
    </item>
    <item>
      <title>CRUD Operations: Object - freeze() | seal() | preventExtensions()</title>
      <link>https://www.webatoms.in/blog/developer-guide/CRUD-Operations-Object-freeze-seal-preventExtensions-J</link>
      <author>Simmi Kava</author>
      <description>### JavaScript: Create | Read | Update | Delete Operations - freeze(), seal(), preventExtensions()  
&lt;br/&gt;

**Object.freeze():-**

This method freezes the object which means new properties cannot be added, existing properties cannot be removed or modified. The enumerability, configurability or writability of existing properties is prohibited. It returns the same object (does not create a copy) that was passed into the function. Also, the frozen object is immutable (not necessarily constant). 

**_Syntax**_  

_Object.freeze(obj)_

Have you heard about _**Shallow Freeze**_?
When you call the method `Object.freeze()` on an `object`, the freeze rules are applicable only to the immediate properties of `object` which implies if the values of these properties are `object` themselves those `objects` are not bound by any rules and are not frozen.


**Object.seal():-**

This method seals the `object` which means it allows to change existing properties but new properties cannot be added to it. Also, all existing properties are marked as non-configurable. But it does not prevent the `value` of data properties from being changed. The `__proto__` property is sealed too.

**_Syntax**_  

_Object.seal(obj)_



**Object.preventExtensions():-**

This method makes the `object` non-extensible i.e. new properties can never be added to an `object`. This process is irreversible i.e. if an `object` is marked as non-extensible, it cannot be reversed. However, properties can still be added to the `object prototype`. 

**_Syntax**_  

_Object.preventExtensions(obj)_

Happy Learning! 
</description>
      <pubDate>Friday, May 14, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/20/linkedin-CRUD-OPERATIONS.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/CRUD-Operations-Object-freeze-seal-preventExtensions-J</guid>
    </item>
    <item>
      <title>JavaScript: Destructuring Assignment [Fail-Safe Destructuring]</title>
      <link>https://www.webatoms.in/blog/developer-guide/JavaScript-Destructuring-Assignment-Fail-Safe-Destructuring-H</link>
      <author>Simmi Kava</author>
      <description>### Destructuring Assignment
&lt;br/&gt;


A JavaScript expressions that allows to unpack properties from objects, values from arrays into distinct variables. 

Let's learn Array destructing with examples.

**Assigning Default Values:-** 

In case the unpacked variable is undefined, a default value can be assigned to the variable. 


```javascript
//ECMAScript 5
var webAtomsList=  [ 10, 20 ];
var f= typeof webAtomsList[0] != "undefined" 
	? webAtomsList[0] : 1;
var s= typeof webAtomsList[1] != "undefined" 
	? webAtomsList[1] : 2;
var t= typeof webAtomsList[2] != 
	"undefined" ? webAtomsList[2] : 3;
var n= typeof webAtomsList[3] != 
	"undefined" ? webAtomsList[3] : undefined;
console.log(f === 10) //true
console.log(s === 20) //true
console.log(t === 3) //true
console.log(n) //undefined 
```


```javascript
//ECMAScript 6
var webAtomsList= [ 10, 20 ];
var [ f = 1, s = 2, t = 3, n] = webAtomsList;
console.log(f === 10); //true
console.log(s === 20); //true
console.log(t === 3) ;//true
console.log(n); //undefined
```

**Output (ECMAScript 5 &amp; 6 is):**
```javascript
true
true
true
undefined 
```

**Variable Swapping:-**  

The destructing assignment of **ECMAScript 6**, allows swapping two values in one destructuring expression. 
```javascript
var first = 1;
var second = 2;
var webAtoms =  [ 10, 20, 30 ];
[webAtoms[2], webAtoms[1]] = [webAtoms[1], webAtoms[2]] ;
console.log(webAtoms);
```
**Output:**
``` javascript
[10,30,20]
```

Without the destructuring assignment swapping values of two variable requires a temporary variable or some XOR-swap trick.


**Variable Assignment:-**

You can assign variable name to values. 
```javascript
var webAtoms =  [ 10, 20, 30 ];
var[ten,twenty,thirty] = webAtoms;
console.log(ten);
console.log(twenty);
console.log(thirty);
```

**Output:**
``` javascript
10
20
30
```

**Assignment separate from declaration:-**

A variable assignment can be done via destructuring, separate from the variable's declaration.

```javascript
var first, second;

[first,second] = [10,20];
console.log(first); 
console.log(second); 
``` 


**Output:**
``` javascript
10
20
```

**Parsing an array returned from a function:-**
```javascript
function webAtoms() {
	return [10,20];
}

var first,second;
[first,second] = webAtoms();
console.log(first); 
console.log(second); 
```
**Output:**
``` javascript
10
20
```

What if you want to ignore some or all the returned values?
Here is how you can do it:-

``` javascript
function webAtoms() {
	return [10,20,30];
}

const [temp,,last] = webAtoms();
console.log(temp);
console.log(last); 
```
**Output:**
``` javascript
10
30
```


**Assign the rest of an array to a variable using spread operator:-**

```javascript
var first,second;
[first,second,...rest] = [10,20,30,40,50];
console.log(first);
console.log(second);
console.log(rest);
```

**Output:**
``` javascript
10
20
[30,40,50]
```


**Unpacking values form a regular expression match:-**

The regular `exec()` method finds a match and returns and array containing
- The entire matched portion of the string
- followed by the string that matches each parentheses group in the regex.

Destructuring comes handy, if you need to unpack the parts of array ignoring the full match if it is not needed. 

```javascript
function parseDate(input) {
  var parsedOutput = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/
  .exec(input);;
  if (!parsedOutput) {
    return false;
  }
console.log(parsedOutput); //["2999-12-31", "2999", "12", "31", index: 0, input: "2999-12-31", groups: undefined]
 

  const [, year, month, day] = parsedOutput;
  return year;
}

console.log(parseDate('2999-12-31')); //2999
```

**Output:**
```javascript
["2999-12-31", "2999", "12", "31"]
2999
```

**Array and Object Destructuring:-**

You can even combine the array and object destructuring. 
Lets learn it with an example. 
``` javascript
var user = [
{id: 1, name: 'Web', programming: 'Phython'},
{id: 2, name: 'Atoms', programming: 'Xamarin.Forms'},
{id: 3, name: 'WebAtoms', programming: 'JavaScript'}
];

var[,,{programming}] = user; //Get 3rd element and skip the other 2
console.log(programming); //JavaScript
```

**Output:**
```javascript
JavaScript
```

Hope you learnt something new today!
</description>
      <pubDate>Wednesday, May 12, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/19/Linkedin-Destructuring.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JavaScript-Destructuring-Assignment-Fail-Safe-Destructuring-H</guid>
    </item>
    <item>
      <title>Dough Crockford's truth table</title>
      <link>https://www.webatoms.in/blog/developer-guide/Dough-Crockford-s-truth-table-G</link>
      <author>Simmi Kava</author>
      <description>##Loose Equality Comparison using ==  
&lt;br/&gt;

- This operator compares two values for equality after converting both the values to a common type.
- It is symmetric in nature. 
- `null` == `undefined` is `true` and so is vice versa.

ECMA Script: All primitives and objects are loosely unequal to `null` and `undefined`.


[Reference: MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness)


</description>
      <pubDate>Wednesday, May 5, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/18/linkedin-Dough-Crockford-s-truth-table-latest.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/Dough-Crockford-s-truth-table-G</guid>
    </item>
    <item>
      <title>Why yield is important in JavaScript</title>
      <link>https://www.webatoms.in/blog/developer-guide/Why-yield-is-important-in-JavaScript-F</link>
      <author>Simmi Kava</author>
      <description>### yield - An important generator function in JavaScript  

&lt;br/&gt;

Before we begin with the theory, let me give you a quick gist of terminologies used to explain the concept. 


**Generator function**

A single function which can be called repeatedly i.e., is iterative in nature and the execution is not a continuous process.  Each generator can be iterated once and upon execution returns a new generator. 

`Generator functions` are powerful tool for asynchronous programming as they alleviate the problems with callbacks.
 

_**Syntax**_ 
```javascript
function* name([param[, param[, ... param]]]) { 

  statements 

}
```

**Producer-Consumer Pattern**

The producer’s job is to generate the data, buffer it and start again. 
The consumer’s job is to consume the data one piece at a time.



**yield**

The `yield` keyword is a generator function and is beneficial in producer-consumer pattern. It is used to pause and recommence a generator function. It cannot be called from nested functions or callbacks; it can be called from the containing generator function only. Execution of `yield` keyword returns an object with two properties: `value` and `done`.

_**Syntax**_ 
```javascript
[rv] = yield [expression]
```


**yield***  

The yield* expression is used to delegate to another iterable object or a generator.

_**Syntax**_ 
```javascript
yield* expression
```



Now, lets take a scenario where you need to know how many files are there on the hard-disk and process them. We may think of two possible approaches here. 
1.	Using an Array
2.	Use a generator function - yield

Let’s learn the pros and cons of both the approaches. 

**1. Using an Array**

If the count is as high as millions, enumerating one million array items, reading them and processing them is not only a waste of CPU time but also memory (consumption would be high). This approach is recommended for smaller chunks of data. 

This is how we would write the logic:

```javascript
function readAllFiles(root) {
    var a = [];
    for(var item of fs.readDir(root)) {
        a.push(item);
        if(fs.isDirectory(item)){
            var children = readAllFiles(item);
            for (const iterator of children) {
                a.push(iterator);
            }
        }
    }
    return a;
}

function processFiles() {

    var a = readAllFiles();
    for (const iterator of a) {
        console.log(a.name);
    }

}

```

For e.g. if each file is ~ 100 bytes, to store 1 million files, we would need 100 mb of memory in addition to storage for book keeping (pointer reference etc.) So, this would amount to approx. 200-500 mb.

As shown in the above piece of code, not only will this approach allocate too many arrays but also if the execution process fails for any reason, essentially no work will be done as we might run into memory errors even before a single file is processed. 
Also, reading time and again is an inefficient approach and would result in to cache busting. 

- **Cache busting** – A process of uploading a new file and replacing a file that is already cached. 

So, to conclude large array enumeration is a bad practice and an expensive operation. 


**2.	Use a generator function - yield**


In such scenarios, generator function comes handy. The generator function will enumerate and return items so that the generator function can process the items and request generator to give next items.

```javascript
function* readAllFiles(root) {
    for(var item of fs.readDir(root)) {
        yield item;
        if(fs.isDirectory(item)) {
            yield *readAllFiles(item);
        }
    }
}

function processFiles() {

    var a = readAllFiles();
    for (const iterator of a) {
        console.log(a.name);
    }

```

As we can see in the above piece of code, no array is allocated. Also, for any reason even if only 50% of items are returned, they will be processed by processFile() function. The processFiles() function will not wait for entire list to be read to process it. 

Hope we learnt something new today. **Keep Learning!**</description>
      <pubDate>Tuesday, May 4, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/16/Linkedin-Why-yeild-is-important-in-JavaScript.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/Why-yield-is-important-in-JavaScript-F</guid>
    </item>
    <item>
      <title>JavaScript Numbers: ∞ -&gt; 0 | ∞ -&gt; maxValue</title>
      <link>https://www.webatoms.in/blog/developer-guide/JavaScript-Numbers-0-maxValue-E</link>
      <author>Simmi Kava</author>
      <description>###JavaScript: Want to know why sometimes ∞ is 0 or ∞ is maxValue?  
&lt;br/&gt;

Numbers are treated differently in JavaScript in different methods. Sometimes `∞` becomes 0, sometimes Infinity becomes `maxValue`. The abstract operation the method uses (of Object/Type/Function) determines the outcome. 


**ToIntegerOrInfinity ( `argument` )**  

**`ToIntegerOrInfinity`** is an abstract operation and takes argument argument. The argument is converted to an `integer`, `+∞`, or `-∞`. The algorithm or rules it follows are listed below:

1. Let number be ? ToNumber(argument).
2. If number is NaN, +0𝔽, or -0𝔽, return 0.
3. If number is +∞𝔽, return +∞.
4. If number is -∞𝔽, return -∞.
5. Let integer be floor(abs(ℝ(number))).
6. If number &lt; +0𝔽, set integer to -integer.
7. Return integer.

**[Reference: ECMAScript Language Specification](https://tc39.es/ecma262/#sec-tointegerorinfinity)**

The `Object/type/function` that uses `ToIntegerOrInfinity` are listed below:


| Object / Type / Function | Integer                 |
|--------------------------|-------------------------|
| String                   | charAt                  |
|                          | charCodeAt              |
|                          | codePointAt             |
|                          | endsWith                |
|                          | includes                |
|                          | indexOf                 |
|                          | lastIndexOf             |
|                          | repeat                  |
|                          | slice                   |
|                          | startsWith              |
|                          | subString               |
|                          |                         |
| Array                    | slice                   |
|                          | splice                  |
|                          | copyWithin              |
|                          | fill                    |
|                          | flat                    |
|                          | includes                |
|                          | indexOf                 |
|                          | lastIndexOf             |
|                          |                         |
| TypedArray               | copyWithin              |
|                          | fill                    |
|                          | includes                |
|                          | indexOf                 |
|                          | lastIndexOf             |
|                          | set                     |
|                          | slice                   |
|                          | subarray                |
|                          |                         |
| SharedArrayBuffer        | slice                   |
|                          |                         |
| Atomics                  | AtomicReadModifyWrite   |
|                          | compareExchange         |
|                          | isLockFree              |
|                          | store                   |
|                          | notify                  |
|                          |                         |
| Date                     | setYear                 |
|                          | UTC                     |
|                          | MakeTime (future)       |
|                          | MakeDay (future)        |
|                          | TimeClip (future)       |
|                          |                         |
| Date Constructor         | Date(...Values)         |
|                          |                         |
| Abstract Operations      | ToLength                |
|                          | ToIndex                 |
|                          |                         |
| String Exotic Objects    | [[OwnPropertyKeys]] ( ) |
|                          |                         |
| Function                 | bind                    |
|                          |                         |
| Number                   | toExponential           |
|                          | toFixed                 |
|                          | toPrecision             |
|                          | toString                |
|                          |                         |
| BigInt                   | toString                |   



&lt;br/&gt;

**SameValueZero ( `x,y` )**    

**`SameValueZero`** is an abstract operation and takes arguments `x` and `y`; where `x` and `y` are ECMAScript language value and returns `[[Value]]` as Boolean and `[[Type]]` as normal. The algorithm or rules it follows are listed below:

1. If Type(x) is different from Type(y), return false.
2. If Type(x) is Number or BigInt, then
a. Return ! Type(x)::sameValueZero(x, y).
3. Return ! SameValueNonNumeric(x, y).

- `SameValueZero` differs from `SameValue` only in the way how it treats +0𝔽 and -0𝔽.

**[Reference: ECMAScript Language Specification](https://tc39.es/ecma262/#sec-numeric-types-number-sameValueZero)**

The `Object/type` that uses `SameValueZero` are listed below:

| Object / Type | SameValueZero         |
|---------------|-----------------------|
| Number Type   | Number::sameValueZero |
|               |                       |
| BigInt Type   | BigInt::sameValueZero |
|               |                       |
| Array         | includes              |
|               |                       |
| TypedArray    | includes              |
|               |                       |
| Map           | delete                |
|               | get                   |
|               | has                   |
|               | set                   |
|               |                       |
| Set           | add                   |
|               | constructor           |
|               | has                   |


Note that, Array method `includes` and `indexOf` are internationally different and use different algorithm to detect `NaN` array elements. Also, any array element which is missing is treated as `undefined`.

&lt;br/&gt;

**ToInt32 ( ` argument`  )**    

`ToInt32` is an abstract operation and takes argument argument. The argument is converted to one of 232 integral Number values ranging from 𝔽(-231) to 𝔽(231 - 1),  The algorithm or rules it follows are listed below:

1. Let number be ? ToNumber(argument).
2. If number is NaN, +0𝔽, -0𝔽, +∞𝔽, or -∞𝔽, return +0𝔽.
3. Let int be the mathematical value whose sign is the sign of number and whose magnitude is floor(abs(ℝ(number))).
4. Let int32bit be int modulo 232.
5. If int32bit ≥ 231, return 𝔽(int32bit - 232); otherwise return 𝔽(int32bit).



- The ToInt32 is an abstract operation that can be applied multiple times without changing the result i.e. it is idempotent. 
- Since, +∞𝔽 and -∞𝔽 are mapped to +0𝔽 the operation ToInt32(ToUint32(x)) = ToInt32(x) 

**[Reference: ECMAScript Language Specification](https://tc39.es/ecma262/#sec-toint32)**

Mostly, majority of other function use `ToInt32` when operating on numbers. 

Hope this article gave insight to few of the JavaScript abstract operations. </description>
      <pubDate>Wednesday, April 28, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/15/linkedin-int32-integer-samevaluezero.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JavaScript-Numbers-0-maxValue-E</guid>
    </item>
    <item>
      <title>JavaScript - try-finally Implementation</title>
      <link>https://www.webatoms.in/blog/developer-guide/JavaScript-try-finally-Implementation-D</link>
      <author>Akash Kava</author>
      <description>###The finally exception handling - Is this a bug?  
&lt;br/&gt;

I found this `finally` block implementation strange! Let's have a look!

```javascript
var a = [1,2,3];
var n = [];
for (let i of a) {
    try {
        (undefined).name();
    } finally {
        n.push(i);
    }
}
console.log(n.toString());
```
The above code raises an `TypeError` on first iteration.

**Output**
```javascript
TypeError: Cannot read property 'name' of undefined
```

I corrected the code and by mistake, I wrote `continue` in the `finally` block instead of `try` block. Here is the code snippet. 

```javascript
var a = [1,2,3];
var n = [];
for (let i of a) {
    try {
        (undefined).name();
    } finally {
        n.push(i);
        continue;
    }
}
console.log(n.toString());
```
When I ran this, above fragment of code did not `throw` any `exception` though it was thrown, but `finally` swallowed it; even though I did not expect it to. In real world scenario, we wouldn't write such logic, but I wasn't expecting `exception` to be swallowed. 

To my surprise **`C#`** does not allow returning anything in `finally` block. The reason being `finally` block is never supposed to override control flow. 

Simplified Code Version:

```javascript
function process() {
           try {
                 throw new Error("catch me if you can");
           } finally {
                 return true;
           }
    }

    try { 
         var e = process();
         if(e) {
               console.log("we cannot catch you");
          }
    } catch (e) {
          console.log("we caught you");
    }
```

Output
```javascript
we cannot catch you
```

Isn't this a bug? 


</description>
      <pubDate>Friday, April 23, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/14/linkedin-finally.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JavaScript-try-finally-Implementation-D</guid>
    </item>
    <item>
      <title>JavaScript: String - Facts Going-over</title>
      <link>https://www.webatoms.in/blog/developer-guide/JavaScript-String-Facts-Going-over-C</link>
      <author>Simmi Kava</author>
      <description>### Did you know : JavaScript String facts?   
&lt;br/&gt;

**1. The String `indices` are `enumerable`.**

Yes, you read it right. Lets learn the same with an example.

***Example:***
```javascript
var str = 'WebAtoms'
var count = '';
for (var i in str) {
count += i;
}
console.log("Array indices: ", count);
```

**Output**
```javascript
01234567
```

**2. Like Array, `String` can be `indexed`.**

***Example***
```javascript
console.log("1st Element: ", 'WebAtoms'[0]);
console.log("2nd Element: ", 
'WebAtoms'[1]);
console.log("3rd Element: ", 'WebAtoms'[2]);
console.log("4th Element: ", new String('WebAtoms')[3]);
console.log("At -1: ", 'WebAtoms'[-1]);
console.log("At Infinity: ", 'WebAtoms'[Infinity]);
console.log("At NaN: ", 'WebAtoms'[NaN]);
console.log("9th Element: ", 'WebAtoms'[8]);

```

**Output**

```javascript
1st Element:  W
2nd Element:  e
3rd Element:  b
4th Element:  A
At -1:  undefined
At Infinity:  undefined
At NaN:  undefined
9th Element:  undefined
```

**3. String `Length` cannot be modified, is read-only but is `enumerable`.**

***Example***

```javascript
console.log("Length: ", 'WebAtoms'.length);
var input='WebAtoms';
console.log("Can Delete? ", delete input.length);
input.length = 10;
console.log("Length remains: ", input.length);
```

**Output**
```javascript
Length:  8
Can Delete?  false
Length remains:  8
```

**4. String `Object` are `modifiable` only beyond the range.**  

Array elements cannot be modified within the range of the String object (can be modified outside the range), but the length remains unchanged.

***Example***
```javascript
var input=new String('WebAtoms');
input[0]= 'H';
console.log("0th element remains unchanged: ", input[0]);
input[9]= 'H';
input[10]= 'i';
console.log("input[9]: ", input[9]);
console.log("input[10]: ", input[10]);
console.log("Length remains unchanged: ", input.length);
```

**Output**
```javascript
0th element remains unchanged:  W
input[9]:  H
input[10]:  i
Length remains unchanged:  8
```</description>
      <pubDate>Wednesday, April 21, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/13/linkedin-STRING.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JavaScript-String-Facts-Going-over-C</guid>
    </item>
    <item>
      <title>Array.Prototype.join() - Why does this work?</title>
      <link>https://www.webatoms.in/blog/developer-guide/Array-Prototype-join-Why-does-this-work-B</link>
      <author>Simmi Kava</author>
      <description>###Why does this work?  
&lt;br/&gt;

**Array.prototype.join()**
The join() method will create and return a new string by concatenating all the elements of an array-like object or an array.

**Syntax:**
arr.join([separator])

**Return Value:**
The output will be a string with all array elements joined. If array length is 0, an empty string is returned.

***Example***
```javascript
var input = { '0': 111, '1': 22, length: 2};
input.join = Array.prototype.join; 
console.log(input.join());
```
**Output**
```javascript
111,22 
```

If we see in the above example, we have provided the length value; hence the return value is a string with all the array elements thereby implying `Array.prototype.join()` is a generic method.

So, can you name other generic methods of Array? Here we go:  &lt;br/&gt;

**Generic Array Methods with Example**

**1. isArray()**

***Example***
```javascript
var $ = {};
$.isArray = Array.isArray;
console.log($.isArray([100]));
```
**Output**
```javascript
true
```
**2. concat()**

***Example***
```javascript
var input = new Number(10);
input.concat = Array.prototype.concat;
console.log(input.concat(20).toString());
```
**Output**
```javascript
10,20
```

**3. pop()**

***Example***
```javascript
var input = { '0': 10, '1': 20, length: 2};
input.pop = Array.prototype.pop;
console.log('input.pop: ', input.pop()); 
console.log('input.length:', input.length); 
console.log(typeof(input[1])); 
```

**Output**
```javascript
input.pop:  20
input.length: 1
undefined
```


**4. push()**

***Example***
```javascript
var x = { '0': 10, '1': 20, length: 2};
x.push = Array.prototype.push;
console.log(x.push(25));
console.log(x[2]);
console.log(x.length);
```

**Output**
```javascript
3
25
3
```

**5. reverse()**

***Example***
```javascript
var input = { '0': 10, '1': 20, length: 2};
input.reverse = Array.prototype.reverse;
console.log(input.reverse() === input); 
console.log("0th element: ", x[0]); 
console.log("1st element:", x[1]); 
console.log("length:", input.length);
```
**Output**
```javascript
0th element:  10
1st element: 20
length: 2
```

***Another Example***
```javascript
var obj = {'0':'-1', '2':'NaN', '4': undefined, '5':undefined, '8':Infinity, 9:true };
obj.length = 10;
obj.reverse = Array.prototype.reverse;
console.log(obj.reverse() === obj);
for (i=0; i &lt; 7;i++)
{
console.log(i + ": " + obj[i]);
}
console.log('7: ',obj[7]);
console.log('8: ', obj[8]);
console.log('9: ', obj[9]);
```
**Output**
```javascript
true
0: true
1: Infinity
2: undefined
3: undefined
4: undefined
5: undefined
6: undefined
7:  NaN
8:  undefined
9:  -1
```

**6. shift()**

***Example***
```javascript
var input = { '0': 10, '1': 20, '2': 30, length: 3};
var input = { '0': 10, '1': 20, '2': 30, length: 3};
input.shift = Array.prototype.shift;
console.log(input.shift());
console.log(input.shift());
console.log('0: ', input[0]);
console.log('1: ', input[1]);
console.log('type of 2nd element: ', typeof(input[2]));
console.log('Length: ', input.length);
```

**Output**
```javascript
10
20
0:  30
1:  undefined
type of 2nd element:  undefined
Length: 1
```

**7. slice()**

***Example***
```javascript
var input = { '0': 10, '1': 20, length: 2};
input.slice = Array.prototype.slice;
var out = input.slice(1);
console.log('0th: ', out[0]);
console.log('type of 1st element: ', typeof(out[1]));
console.log('Length: ', out.length);
```

**Output**
```javascript
0th:  20
type of 1st element:  undefined
Length:  1
```

**8. splice()**

***Example***
```javascript
var obj = {0: 0, 1: 1, 2: 2, 3: 3};
obj.length = 4;
obj.splice = Array.prototype.splice;
var deletedItems = obj.splice(0, 3, 4, 5);
console.log("Length: ", obj.length);
for(i=0;i&lt;3;i++)
{
console.log(i + ": element ", obj[i]);
}
console.log("3rd element: ", obj[3]);
console.log(deletedItems.length);
for(j=0;j&lt;3;j++) {
console.log(j + ": element ", deletedItems[j]);
}
```

**Output**
```javascript
Length:  3
0: element  4
1: element  5
2: element  3
3rd element:  undefined
3
0: element  0
1: element  1
2: element  2
```

Hope you learned something new today!












</description>
      <pubDate>Monday, April 19, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/12/linkedin-arrays-generic-join.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/Array-Prototype-join-Why-does-this-work-B</guid>
    </item>
    <item>
      <title>Comparison of Numbers</title>
      <link>https://www.webatoms.in/blog/developer-guide/Comparison-of-Numbers-A</link>
      <author>Simmi Kava</author>
      <description>###JavaScript: Comparison of 3 Numbers  
&lt;br/&gt;
Ever wondered why the below comparison of numbers gives the following output?

```javascript
1 &lt; 22 &lt; 33
```

**Output:**
```javascript
true
```

But,

```javascript
33 &gt; 22 &gt; 1
```

**Output:**
``` javascript
false
```

Isn't this strange? Well, not really!
``` javascript
33 &gt; 22  //true
```

```javascript
true &gt; 1 // 1 &gt; 1 = false
```

So, how do we fix this? Relational Operator `Greater than or equal operator (&gt;=)`.
```javascript
33 &gt; 22 &gt;= 1
```

**Output:**
```javascript
true
```</description>
      <pubDate>Friday, April 16, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/11/linkedin-number-comparison-javascript-relational.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/Comparison-of-Numbers-A</guid>
    </item>
    <item>
      <title>Modern JavaScript - Proxy</title>
      <link>https://www.webatoms.in/blog/developer-guide/Modern-JavaScript-Proxy-9</link>
      <author>Simmi Kava</author>
      <description>### How to create immutable object using proxy?  
&lt;br/&gt;
**Immutable Object**  

It is an object whose state cannot be modified after it is created.


**Examples of Immutable**  

**`Immutable Data Types in JavaScript`**   

***`Numbers`***&lt;br/&gt;
You cannot change number directly, you need to assign the number to variable and perform an operation on the variable.  &lt;br/&gt; 
***`String`***  &lt;br/&gt; Similarly, you cannot directly modify a particular character in a string. You can create a new string, in case you need to perform any string manipulations.   &lt;br/&gt;
***`Array methods - Map and Filter are immutable`***  &lt;br/&gt;
As this operation requires creation of new array without modifying the original array.

**Advantages of creating immutable object?**
1. More control over your data and predictable data flows and data state.
2. Both Call by reference and call by value can be used.


**What is proxy?**  &lt;br/&gt;
It is standard built-in object that enables you to create a proxy for another object, which can intercept and redefine the fundamental operations for that object.

**Parameters**  &lt;br/&gt;
`target`: Original object  &lt;br/&gt;
`handler`: An object that defines intercepting operations (traps) and their redefination.



**Example**

```javascript
const article = {
	category: "Engineer",
	user: [{firstName: "Web", lastName: "Atoms"}]
};

const immutableObj = (obj) =&gt; {
return new Proxy(obj,{
	get(t,p){
 		return typeof t[p] === "object" ? immutableObj(t[p]) : t[p];
},

	set(){
  	 
  },

});
};

const immutableUser = immutableObj(article);

	immutableUser.user[0] = {firstName: "javascript", lastName: "tutorial"};

	console.log(`${article.user[0].firstName} ${article.user[0].lastName}`);
```

**Output**
```javascript
Web Atoms
```

So to conclude, using proxy allows you to safely pass your objects to any functions without worrying about any modification to the object.
On the downside, using proxy consumes more CPU power. 

Hope this helps! Happy coding. 
</description>
      <pubDate>Wednesday, April 7, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/10/linkedin-proxy-javascript.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/Modern-JavaScript-Proxy-9</guid>
    </item>
    <item>
      <title>Intl.PluralRules</title>
      <link>https://www.webatoms.in/blog/developer-guide/Intl-PluralRules-8</link>
      <author>Ajay Singh</author>
      <description>###Intl.PluralRules    
&lt;br/&gt;


The `Intl.PluralRules` object enables plural-sensitive formatting and plural-related language rules.  
&lt;br/&gt;  

****Syntax****  

`new Intl.PluralRules([locales[, options]])`

****locales [Optional]****  
A string with a BCP 47 language tag (or array of strings).

****options [Optional]****  
localeMatcher  
type   
minimumIntegerDigits  
minimumFractionDigits  
minimumSignificantDigits  
maximumSignificantDigits  

Today, we are going to explain examples using `locales` and `type` parameter.

****type****  
It is the type to use. It can have two values 
"cardinal" - a number that represents amount, such as 1,2,3 rather than order, such as 1st, 2nd, 3rd etc.
"ordinal" - a number such as 1st, 2nd, 3rd, 4th, that shows the position of something in a list of things.

**Using Locales:-**

The below example shows few variations in localized plural rules. 
In order to get the format of the language used in the user interface of your application, 
make sure to specify that language (and some auxiliary languages) using the locales argument:

**Example 1:-**
```javascript
const pr = new Intl.PluralRules('en-US', { type:'ordinal'});
console.log(pr.select(1)); // "one"
console.log(pr.select(2)); // "two"
console.log(pr.select(3)); // "few"
console.log(pr.select(4)); // "other"
```  
**Possible Return Values**
&lt;br/&gt;
```javascript
//The other possible return values are:
zero
one
two
few
many
other
```

Adding suffixes to ordinal numbers ("1st,'2nd' "3rd" 14th, ...") requires custom logic which is often error-prone (specific to each locale!). 
`Intl.PluralRules` now makes our task easier. How? Let us look at another example.


**Example 2:-**   
&lt;br/&gt;
My requirement is that if input contains number such as 1,2,3..., output should display as 1st,2nd,3rd....
Here is the logic for the same. 

```javascript
const pr = new Intl.PluralRules('en', { type:'ordinal'});
const suffix = { one: 'st', two: 'nd', few:'rd', other:'th' }
const numberArray = [0, 1, 2, 3, 4, 56, 42, 32, 33, 560];
numberArray.map((x) =&gt; console.log(`${x}${suffix[pr.select(x)]}`) );

```  
  
&lt;br/&gt;
**Output**
```javascript
//Output

"0th" 
"1st" 
"2nd" 
"3rd" 
"4th" 
"56th" 
"42nd" 
"32nd" 
"33rd" 
"560th" 
```
  
Hope you enjoyed and learned something new today!
</description>
      <pubDate>Monday, April 5, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/9/linkedin-plural-language-rules.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/Intl-PluralRules-8</guid>
    </item>
    <item>
      <title>How do you calculate Match Percentage in an Array?</title>
      <link>https://www.webatoms.in/blog/developer-guide/How-do-you-calculate-Match-Percentage-in-an-Array-7</link>
      <author>Akash Kava</author>
      <description>###JavaScript Code to Calculate Match Percentage in an Array 


&lt;br/&gt;**Array.prototype.some()**   

The `some()` method tests whether at least one element in the array passes the test implemented by the provided function. But it does not provide us any information on `how many` items match or `all` of them match. In fact, as soon as the first item is matched, it returns `true` (****_condition is not evaluated for all the array elements_****).

But what if we have a scenario where want to identify if 
- `all` of them matched, or
- at least `half` of them matched, or 
- `percentage` of matching elements.

Curious to know how can we do it? 

Here is a simple `match` function that we can use with `reduce` to find out the exact matching  percentage. 

```javascript
function match(fx) {
	return function(pv, current, index, array) {
    const fc = fx(current) ? 1 : 0;
    if(index === 1) {
        const fp = fx(pv) ? 1 : 0;
        return fp + fc;
    }
    if(index === array.length - 1) {
        return (pv + fc)/array.length;
    }
    return pv + fc;
  }
}
```

**Output:**

```javascript
// how many items are greater than zero, 
 
console.log(
  [1].reduce(match(x =&gt; x &gt; 0)) 
);  //1 i.e. 100%                                                                               
console.log(
  [0, 1].reduce(match(x =&gt; x &gt; 0))
);  //1 i.e. 100%
console.log(
  [2, 4, 6].reduce(match(x =&gt; x % 2 === 0))
); //1 i.e. 100%
console.log(
  [2, 4, 6, 3].reduce(match(x =&gt; x % 2 === 0))
); //0.75 i.e. 75%
console.log(
  [2, 4, 6, 3, 5].reduce(match(x =&gt; x % 2 === 0))
); //0.6 i.e. 60%
```

Wondering what would be the practical use of this? Machine learning algorithms often depend upon match percentage of different criteria, where such code implementation can be handy.


Hope this helps!
 
</description>
      <pubDate>Wednesday, March 31, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/8/linkedin-calculate-match-percentage.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/How-do-you-calculate-Match-Percentage-in-an-Array-7</guid>
    </item>
    <item>
      <title>Web Atoms Dependency Injection</title>
      <link>https://www.webatoms.in/blog/tutorials/Web-Atoms-Dependency-Injection-4</link>
      <author>Akash Kava</author>
      <description>## Why did we create new one?

Well most dependency injection frameworks available on JavaScript weren't supporting runtime dependency injection. For example, you can load dependency just by giving full module url with package name. And it should be loaded before all dependent modules are loaded in the system.

## Why do we need runtime dependency injection?

1. Mocking - To resolve mocked services on design time
2. Language Resources - Loading language based string resources without worrying about deployment
3. Being able to load dependency from public cdn such as jsdelivr, unpkg etc.

## Registration

To register dependency can decorate class with following attributes.

* DISingleton
* DIScoped
* DITransient

Each attribute lets you declare `mock` and `inject` option for remote path.

```typescript
@DISingleton()
export default class TaskService extends BaseService {

   @Get
   public list(
      @Query("search") search?: string
   ): Promise&lt;ITaskModel[]&gt; { return null; }

}
```

This will register this class itself for its own dependency.

### Mock

```typescript
@DISingleton( { mock: "./mocks/MockTaskService" } )
export default class TaskService extends BaseService {

   @Get
   public list(
      @Query("search") search?: string
   ): Promise&lt;ITaskModel[]&gt; { return null; }

}
```

This is interesting, while in design time, `TaskService` dependency will be resolved against `MockTaskService` sitting in mocks folder which is relative to current module. And Web Atoms' own module loader takes care of loading this dependency at runtime before current module is fully loaded.

```typescript
export default class MockTaskService extends TaskService {

   public list(
      search?: string
   ): Promise&lt;ITaskModel[]&gt; { 
      return this.sendResult([ /* mock result */... {} ]); 
   }

}
```

### Abstract class

If you have different dependencies for different platforms, they can be injected as follow, please note `{platform}` will be `web` for browser and `xf` for Xamarin.Forms

```typescript
@DISingleton( {
   inject: "./{platform}/LocalStorageService",
   mock: "./mock/MockStorageService"
})
export default abstract class StorageService {

   public abstract store(key: string, value: any): Promise&lt;void&gt;;

   public abstract read&lt;T&gt;(key: string): Promise&lt;T&gt;;

}
```

Now this is interesting, while in design time, `MockStorageService` will be resolved for `StorageService` irrespective of the platform you are testing. And on runtime, for Web, it will resolve `./web/LocalStorageService` and for Xamarin.Forms it will resolve `./xf/LocalStorageService`.

## Implementation in different module

```typescript
@DISingleton({
   mock: "./mocks/MockAuthService",
   inject: "@private-packages/user/dist/{platform}/UserAuthService"
})
export default abstract class AuthService {
}
```

In this case, your implementation can be in different module altogether.

### Language Resources

Making your application support multiple languages is a prime requirement now days. Web Atoms makes it very easy with Dependency Injection.

In the following example, we want to inject class based on the current selected language by user.

```typescript
@DISingleton({ inject: "./{lang}/StringResource" })
export abstract class BaseStringResource {
    public abstract get username(): string;
}
```
/en-us/StringResource class

```typescript
export default class StringResource extends BaseStringResource {
    public username = "Username";
} 
```
/hi/StringResource class

```typescript
export default class StringResource extends BaseStringResource {
    public username = "यूज़र नेम";
} 
```

## Injection

### Constructor Injection

```typescript
export default class TaskListViewModel extends AtomViewModel {

    // constructor injection..
    constructor(
        @Inject app: App,
        @Inject private taskService: TaskService,
        @Inject private stringResource: StringResource)
    {
        super(app);
    }
}
```

Though rewriting constructor on every view model becomes little tedious so we also support property injection, but injected properties are not available in constructor. So we created `init` method which will be called after view model has been constructed and all injected properties are available.

### Property Injection

```typescript
export default class TaskListViewModel extends AtomViewModel {

    @Inject
    public taskService: TaskService;

    @Inject
    public stringResource: StringResource;

}
```

## App

App class is derived from ServiceProvider and it acts as a service container. Every control and every view model must receive app in construction injection for web atoms to function correctly.</description>
      <pubDate>Tuesday, March 30, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/5/Dependency-Injection.png</image>
      <guid>https://www.webatoms.in/blog/tutorials/Web-Atoms-Dependency-Injection-4</guid>
    </item>
    <item>
      <title>Simple and Complex Validations in Web Atoms</title>
      <link>https://www.webatoms.in/blog/tutorials/Simple-and-Complex-Validations-in-Web-Atoms-5</link>
      <author>Akash Kava</author>
      <description>Data validation in User Interface is crucial for every application and Web Atoms makes it very easy to write.

## Simple Validation

Validation accessor is decorated with `@Validate` decorator and it is prefixed with the word `error`. You can bind these accessor in UI to display errors.

For example,

```typescript

export default SignupViewModel extends AtomViewModel {

    @Inject
    public navigationService: NavigationService;

    public model = {
        firstName: null,
        lastName: null
    };

    // both validate properties will return undefined value
    // unless `this.isValid` is referenced.

    @Validate
    public get errorFirstName(): string {
        return this.model.firstName ? "" : "First name is required";
    }

    @Validate
    public get errorLastName(): string {
        return this.model.firstName ? "" : "Last name is required";
    }

    public signup(): Promise&lt;void&gt; {

        // as soon as this property is called first time
        // validation decorator will update and error will be displayed
        if (!this.isValid) {
            await this.navigationService.alert(`Please enter required fields`);
            return;
        }

        // optional, if you want to reuse same form
        // you can call resetValidations to remove all errors
        this.resetValidations();
    }

}

```
TSX for Web
```tsx
class Component extends AtomControl {

   public viewModel: SignupViewModel;

   public create() {
       this.viewModel = this.resolve(SignupViewModel);
       this.render(
&lt;div&gt;
    &lt;input 
        placeholder="First name:"
        value={Bind.twoWays(() =&gt; this.viewModel.model.firstName)}/&gt;
    &lt;span
        class="error"
        text={Bind.oneWay(()) =&gt; this.viewModel.errorFirstName}/&gt;

    &lt;input 
        placeholder="Last name:"
        value={Bind.twoWays(() =&gt; this.viewModel.model.lastName)}/&gt;
    &lt;span
        class="error"
        text={Bind.oneWay(()) =&gt; this.viewModel.errorLastName}/&gt;

    ...

    &lt;button
        eventClick={ () =&gt; this.viewModel.signup() }&gt;Signup&lt;/button&gt;

&lt;/div&gt;
       );
   }

}
```

TSX for Xaml
```tsx
class Component extends AtomControl {

   public viewModel: SignupViewModel;

   public create() {
       this.viewModel = this.resolve(SignupViewModel);
       this.render(
&lt;XF.StackLayout&gt;
    &lt;XF.Entry
        placeholder="First name:"
        text={Bind.twoWays(() =&gt; this.viewModel.model.firstName)}/&gt;
    &lt;XF.Label
        class="error"
        text={Bind.oneWay(()) =&gt; this.viewModel.errorFirstName}/&gt;

    &lt;XF.Entry 
        placeholder="Last name:"
        text={Bind.twoWays(() =&gt; this.viewModel.model.lastName)}/&gt;
    &lt;XF.Label
        class="error"
        text={Bind.oneWay(()) =&gt; this.viewModel.errorLastName}/&gt;

    ...

    &lt;XF.Button
        command={ () =&gt; this.viewModel.signup() }
        text="Signup"/&gt;

&lt;/XF.StackLayout&gt;
       );
   }

}

```

In above example, when page is loaded, error spans will not display anything. Even if `firstName` and `lastName` both are empty. As soon as user clicks `Signup` button, `this.isValid` get method will start watching for changes in all `@Validate` decorator methods and user interface will start displaying error message.

## Multi View Model Validation
Larger UI will need multiple smaller UI Components, in Web Atoms, you can easily create a UI with View Model that references parent view model, parent view model's validation extends to children and it return false for `isValid` even if children view models are not valid.

### Root Insurance View
```typescript
interface IInsurance  {
    id?: number;
    date?: Date;
    broker: string;
    type: string;
    applicants: IApplicant[];
}

export interface IApplicant {
    name: string;
    type: string;
    address?: string;
    city?: string;
}

export default class InsuranceViewModel extends AtomViewModel {

    @Inject
    public navigationService: NavigationService;

    public model: IInsurance = {
        broker: "",
        type: "General",
        applicants: [
            {
                name: "",
                type: "Primary"
            }
        ]
    };

    @Validate
    public get errorBroker(): string {
        return this.model.broker ? "" : "Broker cannot be empty";
    }

    public addApplicant(): void {
        this.model.applicants.add({
            name: "",
            type: "Dependent"
        });
    }

    public async save(): Promise&lt;void&gt; {
        if (!this.isValid) {
            await this.navigationService.alert("Please fix all errors", "Error");
            return;
        }
        await this.navigationService.alert("Save Successful", "Success");
    }

}
```
#### Insurance.html

We are displaying list of applicants in Insurance form, and we can add more applicants, note, each applicant's validation will be different based on type of applicant.

```tsx
export default class Insurance extends AtomControl {

   public create(): void {
      this.viewModel =  this.resolve(InsuranceViewModel) ;

      this.render(
      &lt;div&gt;
         &lt;div&gt;
            &lt;input
               placeholder="Name"
               value={Bind.twoWays((x) =&gt; x.viewModel.model.broker)}&gt;
            &lt;/input&gt;
            &lt;span
               style="color: red"
               text={Bind.oneWay((x) =&gt; x.viewModel.errorBroker)}&gt;
            &lt;/span&gt;
         &lt;/div&gt;
         &lt;AtomItemsControl
            items={Bind.oneTime((x) =&gt; x.viewModel.model.applicants)}&gt;
            &lt;AtomItemsControl.itemTemplate&gt;
               &lt;Applicant&gt;
               &lt;/Applicant&gt;
            &lt;/AtomItemsControl.itemTemplate&gt;
         &lt;/AtomItemsControl&gt;
         &lt;button
            eventClick={Bind.event((x) =&gt; (x.viewModel).addApplicant())}&gt;
            Add Applicant
         &lt;/button&gt;
         &lt;div&gt;Other fields...&lt;/div&gt;
         &lt;button
            eventClick={Bind.event((x) =&gt; (x.viewModel).save())}&gt;
            Save
         &lt;/button&gt;
      &lt;/div&gt;
      );
   }
}
```

### Nested Applicant View
Typescript
```typescript
export default class ApplicantViewModel extends AtomViewModel {

    @Inject
    public navigationService: NavigationService;

    public model: IApplicant;

    @Validate
    public get errorName(): string {
        return this.model.name ? "" : "Name cannot be empty";
    }

    @Validate
    public get errorAddress(): string {
        return this.model.address ? "" : "Address cannot be empty";
    }

    public async delete(): Promise&lt;void&gt; {
        if (!( await this.navigationService.confirm("Are you sure you want to delete this?") )) {
            return;
        }
        (this.parent as InsuranceViewModel).model.applicants.remove(this.model);
    }
}
```
#### Applicant.html

Applicant view is an independent view with its own view model, and it can also be used without parent list.

```tsx
export default class Applicant extends AtomControl {

   public create(): void {

       /** Following method will initialize and bind parent property of
        * ApplicantViewModel to InsuranceViewModel, this is specified in the form
        * of lambda so it will bind correctly after the control has been created
        * successfully.
        *
        * After parent is attached, parent view model will include all children validations
        * and will fail to validate if any of child is invalid
        */
      this.viewModel =  this.resolve(ApplicantViewModel, () =&gt; ({ model: this.data, parent: this.parent.viewModel })) ;

      this.render(
      &lt;div
         style="margin: 5px; padding: 5px; border: solid 1px lightgray; border-radius: 5px"&gt;
         &lt;div&gt;
            &lt;input
               placeholder="Name"
               value={Bind.twoWays((x) =&gt; x.viewModel.model.name)}&gt;
            &lt;/input&gt;
            &lt;span
               style="color: red"
               text={Bind.oneWay((x) =&gt; x.viewModel.errorName)}&gt;
            &lt;/span&gt;
         &lt;/div&gt;
         &lt;div&gt;
            &lt;input
               placeholder="Address"
               value={Bind.twoWays((x) =&gt; x.viewModel.model.address)}&gt;
            &lt;/input&gt;
            &lt;span
               style="color: red"
               text={Bind.oneWay((x) =&gt; x.viewModel.errorAddress)}&gt;
            &lt;/span&gt;
         &lt;/div&gt;
         &lt;button
            eventClick={Bind.event((x) =&gt; (x.viewModel).delete())}&gt;
            Delete
         &lt;/button&gt;
      &lt;/div&gt;
      );
   }
}
```

&gt; When a child view is created, we are assigning parent as visual parent's view model. So whenever this child view is invalid, even parent will be invalid.


</description>
      <pubDate>Tuesday, March 30, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/6/Validation.png</image>
      <guid>https://www.webatoms.in/blog/tutorials/Simple-and-Complex-Validations-in-Web-Atoms-5</guid>
    </item>
    <item>
      <title>Spread with Set to remove duplicates from an Array</title>
      <link>https://www.webatoms.in/blog/developer-guide/Spread-with-Set-to-remove-duplicates-from-an-Array-6</link>
      <author>Simmi Kava</author>
      <description>### Spread &amp; Set


Did you know there is a simple way to remove duplicates (i.e. get unique values) from an array using **Spread** operator and **Set** object. Here is how you can do it:-


```javascript
var inputArray = [21, 44, 44, 66, 10, 777, 777, 777,80, 66, 21];
var outputArray = [...new Set(inputArray)];
```


**Output:**
```javascript
console.log(outputArray); //[21, 44, 66, 10, 777, 80]
```

Hope this helps!</description>
      <pubDate>Tuesday, March 30, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/7/Linkedin-Remove-duplicates-in-array.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/Spread-with-Set-to-remove-duplicates-from-an-Array-6</guid>
    </item>
    <item>
      <title>Null and NaN</title>
      <link>https://www.webatoms.in/blog/developer-guide/Null-and-NaN-3</link>
      <author>Simmi Kava</author>
      <description>##JavaScript Oddities - Null and NaN


```javascript
console.log(typeof null) //object
console.log(null instanceof Object) //false
```

We all know that value `null` represents intentional absence of any object value. `typeof` would return a string, hence `typeof` `null` returns object. This is a historical bug (s_ince the first version of JavaScript_) and cannot be fixed.

But since `null` is absence of value, it implies it cannot be instance of anything, hence `instanceof` returns a `false` value.

Similarly,
```javascript
console.log(typeof NaN) //Number
console.log(NaN === NaN) //false
```

`NaN` is a number from data type point of view. `NaN` is a special number as specified by IEEE format specification and is not JavaScript language specific. `NaN` is never equal to `NaN`, as each `NaN` is unique unknown number. </description>
      <pubDate>Wednesday, March 17, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/4/linkedin-null-nan-1200-628.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/Null-and-NaN-3</guid>
    </item>
    <item>
      <title>Is 'instanceof' an expensive operation in JavaScript </title>
      <link>https://www.webatoms.in/blog/developer-guide/Is-instanceof-an-expensive-operation-in-JavaScript-2</link>
      <author>Simmi Kava</author>
      <description>As we know `'instanceof'` allows to check type of object at run time which may be necessary in few cases. 

So, is it an expensive operation in JavaScript? It may be an expensive operation in certain scenario. Let's learn how and why? 


```javascript
class Shape {

}

class Circle extends Shape{

}

var c = new Circle();

// this is one step call
if(c instanceof Circle) {

}

// this is two step call
if(c instanceof Shape) {

}

// this is three step call
if(c instanceof Object) {

}
```

why is the below a two step call?
```javascript
// this is two step call
if(c instanceof Shape) {

}
```
**Why?**

This is how you have to traverse to verify if c is instance of shape
```javascript
c.__proto__ === Shape  //false
c.__proto__.__proto__.constructor === Shape //true
```

The deeper you want to traverse, complex it becomes. So, what is the suggested alternative to 'instanceof'? Object notation as shown below:-

```javascript
var c1 = {
    isCircle: true,
    isShape: true
};

// this is single step call
if(c1.isCircle) {

}

// this is single step call
if(c1.isShape) {

}
```


Even `Esprima` and `Typescript` compiler do not use classes approach as they are slow to construct compare to object. 

&lt;b&gt;Why?&lt;/b&gt;

As each creation will require super to be executed. So, when you have too many number of items, it will be slow to create and slow to inspect. 

So to conclude, avoid using `'instanceof'` when number of elements to inspect are very high. </description>
      <pubDate>Tuesday, March 16, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/2/linkedin-instance-of-1200-627.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/Is-instanceof-an-expensive-operation-in-JavaScript-2</guid>
    </item>
    <item>
      <title>JavaScript Class Restrictions</title>
      <link>https://www.webatoms.in/blog/developer-guide/JavaScript-Class-Restrictions-1</link>
      <author>Akash Kava</author>
      <description>## Did you know JavaScript has Class restrictions?   &amp;nbsp;   
 





```javascript
// compilation error
    var a = () =&gt; null;
    class A extends a {
    }
```

**Q)** Why does the above code give compilation error even though A extends a function?  &amp;nbsp;   
 
**A:** Lamda function (arrow function) does not have a prototype, hence cannot be used as a super; thereby implying you cannot extend from such class. 

```javascript
// compiles but creating new instance fails
    var n = null;
    class B extends n {
    }
```

**Q)** Why does the above code compile, but gives error when we  try to create an instance?  &amp;nbsp;   

**A:** null value is an object in JavaScript, hence it doesn't give syntax error. But creating an object fails because it is not a function. 

```javascript
   //compilation error
    var a = 1;
    class A extends a {
    }

   //compilation error
    var a = Object(1);
    class A extends a {
    }

   //compilation error
    var a = ({});
    class A extends a {
    }
```
In all of the above, none of the value is a function, hence will give a compilation error. 


&gt; **Note**

In `c#`, `java`, `c++` etc. **base class** cannot be a **variable**. It has to be available at compile time. In `javascript`, everything is a **&lt;em&gt;first class citizen&lt;/em&gt;** (function and classes are run-time variables). The above code can only be written in `javascript`. </description>
      <pubDate>Monday, March 15, 2021</pubDate>
      <image>https://cdn-web-atoms.8ct.co//api/attachments/att/1/linkedin-js-class-restrictions-1200-627.png</image>
      <guid>https://www.webatoms.in/blog/developer-guide/JavaScript-Class-Restrictions-1</guid>
    </item>
  </channel>
</rss>