Thursday 14 May 2015

Web Components Flavored With KnockoutJS

Peter: So, Do you heard about web components?

Hamed: Yes, web components are reusable user interface widgets that are created using open web technology. But I think it is still a draft paper and not all browsers support it.

Peter: You mean that we can not use it?

Hamed: I think yes, we can not use it for now but if you deal with knockout library you can create something like Web Component Concept Called "Component".

Peter: And what do you think about it?

Hamed: Components are a clean way to organize your UI code into self-contained, reusable widgets. They combine a template and data (the ViewModel) for rendering on the page. components introduce to you some features like:

  • Components can represent individual controls or a huge section of your application.
  • Contain their own view, can use the main ViewModel or can use their own.
  • You can send parameters to it.
  • Can Easily be packaged for reuse across projects.
  • Can be preloaded or loaded asynchronously (via AMD or other module systems) on demand.
Peter: How can we use it or how to create it?

Hamed: The easiest way to create a component is to use ko.components.register, a function for register a component to the knockout so you can use it normally at your view.

We have an example, we will create components contain a login module (two textboxes and button) by clicking on on the button welcome message will show to the user. You can see it by following this link:


As the above example, we support the function with the following parameters,

  • Component name
  • Component view model
  • Component view ( HTML Markup)

The normal way, of course, we need to support ViewModel and view using external files not to be embedded inside the component. 
In most applications, you’ll want to keep component view models and views in external files.
If you configure Knockout to fetch them via an AMD module loader such as require.js, then they can either be preloaded (possibly bundled/minified), or incrementally loaded as needed.
We can use the component with two ways
  • Using the component binding ( <div data-bind='component: "login-component"'></div>).
  • Using a custom element. (<login-component></login-component>).
Peter: mmmmm, interesting topic to apply, but I believe that there are advanced options and configurations to work with it.

Hamed: Yes, of course, knockout introduces it with rich options so we can use it at advanced level. Next Lesson we will explain as much as we can these options :)


References
https://developer.mozilla.org/en-US/docs/Web/Web_Components
http://knockoutjs.com/