Step by Step implementing Two-Way Data Binding in Vanilla JavaScript

Data Binding is one of the most important features of all the frameworks. It ensures that the data model and the views are in sync with each other. It is very fundamental feature of any MV* frameworks such that Model-View-Controller, Mode-View-ViewModel, and Model-View-Presenter, etc.

Popular JavaScript based frameworks such that React, Angular have their way to implement it. However, it is a good idea to know how a basic two-way data binding can be implemented using vanilla JavaScript.  That would give you an overview of how much heavy lifting is done by the framework when you use features like data binding.

To get most of this post, you should have a basic understanding of following JavaScript features

  • Creating an object as literal
  • Adding a property with Object.defineProperty
  • Using setter and getter
  • forEach statement

 

You can refresh about JavaScript object creation in this video on geek97. Let us get started,

On the HTML, we have put one input text box and two span elements.  Whenever the user enters a value in the text box, data in <span> element should get updated.

We are going to write JavaScript for data binding in the databinding.js file, so we also added a reference to that in the HTML.

To start with databinding.js file contains an Immediately Invoked Function Expression (IIFE). We write all the codes inside this function,

At this point, on launching the application, you should get below output. Right now, if you enter anything in the Name field nothing would be affected.

cd1

Note: If you are using Visual Studio Code, install the extension Live Server, and run the HTML in the browser, right click on the file and from the context menu select “Open with Live Server” to launch the application.

Our first task is to select all the elements which have [data-geek97-bind] attribute set, and also check for their type. Right now, as we are creating binding only for input type text, so we can make a selection of elements and type checking as shown below,

We have created an empty object called dbrepo, which would maintain the state between the data bound elements. The dbrepo object would make sure that all DOM elements with [data-geek97-bind] attribute set to value ‘name’ is in sync and have the same value.

To achieve that, what all we need to do is to add a property dynamically to the dbrepo object for each unique value of [data-geek97-bind] attribute in the DOM elements. For that, let us create a function called addToScope. In the function, we check whether a particular property exists or not, if not then using the Object.defineProperty() method adds a property to the dbrepo object.

Using the hasOwnProperty() method, determining whether property already exists or not, if not then add it using the Object.defineProperty() method. You can learn more about property descriptor and Object.defineProperty() here

We need to do some work in the setter function.

  • First, find all the elements with data-geek97-bind attribute set to the same value.
  • If the element type is text, set its value, otherwise set innerHtml of the element

Above two tasks can be performed in the setter function as below,

Putting everything together, code to perform two-way data binding is as below:

If you want to change the value in the code by just rewriting the value of the property in the dbrepo object,

At this point, on launching the application you should get below output. Right now, if you enter anything in the Name field, the other two spans would be affected.

cd2

Still, there is scope for much improvement in this code,

  1. Instead of rewriting the innerHtml, append the next text
  2. Extend it for other types than text.

I hope you find this post useful. Thanks for reading.

 

All about types of Action Results in the Web API

While building an API, the client should receive a proper and descriptive HTTP response message for each request. The Web API provides a very simple approach to achieve this.  A Web API controller action can return the following types:

  1. void
  2. HttpResponseMessage
  3. IHttpActionResult
  4. Other types, such as IEnumerable, object, collections, etc.

action result type

To test these different types and HTTP response message associated with them, I will use REST client tool Postman.

The void type

If the return type is set to void, Web API returns an empty HTTP response message with status code 204 means no content.  Let us create an action, which returns void,

In the Postman, on performing HTTP Post operation, you will get response as shown next:

typeinactionresult2

The HttpResponseMessage type

HttpResponseMessage type represents a HTTP response message which encapsulates data and the status code. Besides status code, you can also set other properties such that,

  • Content
  • Headers
  • IsSucessStatusCode
  • ReasonPhrase
  • RequestMessage
  • Version

You can return HttpResponseMessage with certain properties set as shown below:

 

So, /api/data returns HtppResponseMessage, which has content, status code, Reason Phrase to be sent with the code, and cache control set. In the postman, you will get a response header as shown below. Also, you will notice that the status code contains Reason Phrase, “Data is processed.”

typeinactionresult3

Also, the response would be cached for 20 milliseconds. You can also use the HttpResponseMessage type to send data into the response body. It uses media formatter to serialize the data in the format passed as the accept header of the HTTP request.  For example, training data can be sent in the body of HttpResponseMessage as shown below,

Now, in the postman client, if you set Accept Header of Request to application/XML as shown in below image,

typeinactionresult4

In the response body, you will get training data from the API serialized as XML,

typeinactionresult5

Whereas if you set Accept Header of Request to application/JSON as shown in below image,

typeinactionresult6

In the response body, you will get training data from the API serialized as JSON,

typeinactionresult7

The IHttpActionResult type

The third type is IHttpActionResult, which was introduced in Web API 2.0. It provides, a factory to construct an HttpResponse message. It allows you to construct HTTP responses in a separate class, such that controllers can be better unit tested.

You can use IHttpActionResult in two ways:

  1. Implement it in a separate class to construct the HTTP response.
  2. Directly Use IHttpActionResult defined in System.Web.Http.Results namespace.

Often, you can use IHttpActionResult to return a particular data in this case training as shown below,

IHttpSActionResult from System.Web.Http.Results provides two methods to return result from the action.

  1. NotFound
  2. Ok

As you see, GetTraining action returns data wrapped in Ok method, or NotFound, if training with given id does not exist.

In the postman client, if you pass id value to 1 as shown in the below image, you will get an HTTP response with status 404 Not Found, as there is no training with id 1 exist.

typeinactionresult8

You can also create an HTTP response message in a separate class.  By doing that, you hide low-level details of HTTP response message construction from the controller class and can also reuse the code to construct an HTTP response message. To do this,

  • Implement IHttpActionResult interface in the class
  • Define ExecuteAsync method

We can implement IHttpActionResult to return a list of trainings in the HTTP response message, as shown below:

We are, setting various properties of the HttpResponseMessage in the ExecuteAsync method. To return list of trainings as content of the HTTP response message, we are creating object of ObjectContent and using JSONMediaTypeForammter to convert list of training in a JSON format.

Now you can use newly created TrainingDataResponse in the controller class as shown below:

Now you can test it in the postman client as shown in the image below,

typeinactionresult9

Other Types

Besides the above three types, you can use any other types such as IEnuenrable<T>, List<T>, etc. To return them as HTTP response Web API uses the media formatter to serialize the returned data. Web API will write the serialized data in the body of the Http response, and set the status to 200.

Below action returns trainings, which is serialized by Web API,

In the postman, you can test it as shown below:

typeinactionresult11

Conclusion

These are the types supported by Web API. You should use them as per your requirement.  For example, to construct low level details of HTTP response message, use the type HttpResponseMessage, and to send serialize data with status code 200, use the other types such as IEnumerable<T>.

Goodbyes are hard…..

Yes, Goodbyes are hard. After almost 5 years at Infragistics, I am moving on and seeking other opportunities. I must say these years were the best years of my life.


clip_image002

At Infragistics, I was a Developer Evangelist. My job was to engage developers, create more awareness with them around Infragistics’ Ignite UI product, and to help them to be successful.   Here are some of the things I accomplished : 

  • I created a developer community for Infragistics in India
  • I helped customers to learn and implement their solutions using Ignite UI
  • I delivered many workshops and talks across India for customers on JavaScript,  Angular, Ignite UI, ASP.NET MVC and more.
  • I created samples and customer POCs
  • I wrote articles for Infragistics blog. You can read them here

As a remote employee, I worked with various teams, managers, and regions. Based on that experience, I can say that Infragistics is one of the best employers and lead by true thought-leaders. They truly believe in making their customers successful and take care of their employees. I am grateful for my time at Infragistics, and want to send a special thanks to Senior Vice President Jason Beres for his trust in me, and giving me the opportunity. 

image

Other people I would like to thank is Director of Product Developer Konstantin Dinev , Managing Director of APAC Ken Azuma , Director of India Rohit Gaur , and my first manager Anand Raja for their constant support.

What’s Next?

I have been a Developer Evangelist for the last 7 years, helping Progress Telerik and Infragistics create their developer base in India. My forte is evangelism and I want to continue helping in reaching and educating developers and in creating community.

If you are looking for someone to help you engage with, enable, and excite your developers, feel to reach me at debugmode[at]outlook.com or tweet me at @debug_mode