CanJS for Flexible and Powerful Javascript Frameworks to Build Complex Apps

What is CanJS?

CanJS is a lightweight, modern JavaScript MVVM framework, for building web applications, that provides a lightweight inheritance system, observable objects and values, and a powerful MVC core, with live-bound templates, among other resources. It makes developing complex applications simple and fast. Easy-to-learn, small, and unassuming of your application structure, but with modern features like custom tags and 2-way binding, creating apps is easy and maintainable.

CanJS is composed of following modules which are typically distributed as part of the core framework:

Setting up CanJS

CanJS can be downloaded or installed in many ways:

  • npm
  • the zip download (available on www.canjs.com)
  • load from canjs cdn
  • bower

Once downloaded or installed, CanJS can be loaded in a variety of ways:

  • StealJS,
  • RequireJS
  • Browserify
  • <script> tags

Here, I will explain one of the methods – i.e: using StealJS and NPM. (other ways of setting up canjs)

To use StealJS and CanJS, install the can, steal and jQuery packages:

> npm install can --save
 > npm install steal --save
 > npm install jquery --save

Create a stache template for your app:
File name: main.stache

&lt;h1&gt;{{message}}&lt;/h1&gt;

Create a main module for your application. Import CanJS’s core, jQuery, and your template.

File name: main.js

import can from "can";
 import $ from "jquery";
 import template from "./main.stache!";

var data = new can.Map({message: “Hello World”});

$(“body”).append(template(data));

Finally, create a page that loads js and specifies “main” as the main module:

<html>
 <body>
 <script src="./node_modules/steal/steal.js" data-main="main"></script>
 </body>
 </html>

Observables

Observables are special types of objects that can be observed and which respond to changes in their values. Observables are used to bind controllers to view in MVC structure of CanJS. Whenever an observable’s value is changed it will be reflected in the view automatically.

There are two kinds of observables in the core of CanJS objects.

  1. Map – used to create Objects
  2. List – used to create Arrays

Creating Instances

var employee = new can.Map({ name:’John’, eid:1234 });
 employee.attr(‘name’); // John

var cityList = new can.List([‘Ahmedabad’,’Bangalore’,’Chennai’,‘Delhi’]);
cityList.attr(2); // Chennai

Manipulating properties

The attr method is used to read a property from, or write a property to an Observale Object and List.

var employee = new can.Map({ name:’John’, eid:1234 });
 employee.attr(‘name’); // John
 employee.attr(‘name’,’Bob’);
 employee.attr(‘name’); // Bob

employee.attr({eid:3456, department: ‘Finance’});
employee.attr(); // {name: ‘Bob’, eid: 3456, department: ‘Finance’});


Responding to changes

When a property of an Observable  object is changed, it emits an event with the changed property name, its old value and new value.

var employee = new can.Map({ name:’John’, eid:1234 });
 employee.bind(‘name’, function(event, newVal, OldVal){
 console.log(oldVal); // ‘John’
 console.log(newVal); // ‘Bob’
 });
 employee.attr(‘name’, ‘Bob’);

Stache templates

Stache templates look similar to normal HTML, but they contain optimized tags that contain a very simple language that can be used –

  • lookup and insert values into the html output
  • loop over arrays and can.Lists
  • control-flow behavior like if and switch
  • render other templates with partials
  • perform custom control-flow behavior

Components

Component is an individual entity in an application which is encapsulated with its own view template, Javascript file and CSS file. A Component lets you reuse them across projects.

How to create a Component?

  1. To create a component first you need to import can.Component library.
  2. create a component – js
can.Component.extend({
 tag: 'my-first-component',
 template:can.view(my_first_component.stache'),
 viewModel: {
 message: 'Hello reader. Welcome to CanJS!'
 }
 });

Create a template and bind a view-model to it.

&lt;h1&gt;{{ message }}&lt;/h1&gt;

Finally, we need to add reference to this component in tinde.html with a script tag.

&lt;script src = "my_first_component.js"&gt;&lt;/script&gt;

In my next blog I will cover Routing and Event handling in CanJS.

AngularJS – A Structural Framework for Dynamic Web Applications [Part 2]

As I mentioned in my earlier blog A Structural Framework for Dynamic Web Applications [Part 1], AngularJS is an open source web application framework to build large scale and high performance web applications while keeping them easy to maintain. It provides developers options to write client-side application in a clean Model View Controller (MVC) architecture. AngularJS automatically handles JavaScript code suitable for different browsers and so, the developer does not have to make his JavaScript application cross-browser compliant.

In my previous blog A Structural Framework for Dynamic Web Applications [Part 1], I focused on Controller and Directives. In this blog I will delve into Dependency Injection and Services.

Dependency Injection

AngularJS has a built-in dependency injection subsystem, which lets the developer to specify the dependencies as parameter to the controller. Dependency injection takes care of injecting the specified dependency and makes the developer’s job easier.

There are many AngularJS core services which can be accessed by injecting to the controller as parameter. AngularJS will detect that you need that service and provide you an instance of it. In the following example $http, $location are dependencies injected to the controller MyController.

angular.module (“myApp”,[]).controller(“MyController”,function($scope, $location){
 // body of the controller
 });

Services

Services are JavaScript functions which are used to perform a particular task. Services are injected into the controllers using AngularJS’s dependency injection mechanism.  Services are individual entity which is easily maintainable and testable.  AngularJS provides many built-in services, for example $http to make AJAX call to the server, $route to define routing configuration, etc. Let’s understand this with an example.

Step-1: Create a template

<div ng-app=" myApp" ng-controller="MyController">
 <p>Enter a number: <input type="number" ng-model="number" /></p>
 <button ng-click="getSquare()">Square</button>
 <p>Result: {{result}}</p>
 </div>

Step-2: Create a service

var app = angular.module('myApp', []);
 app .service('MathService', function(){
 this.square = function(a) {
 return a * a;
 }
 });

The above service has a method “square” which accepts a number and returns its square.

Step-3: Inject the above service to the controller

var app = angular.module('myApp', []);
 app .controller('MyController', function($scope, MathService) {
 $scope.getSquare = function(){
 $scope.result = MathService.square($scope.number);
 }
 });

Result

In the above controller MathService is injected and square method is called using this injector which returns square of a given number.

AngularJS – A Structural Framework for Dynamic Web Applications [Part 1]

AngularJS is an open source web application framework to build large scale and high performance web applications while keeping them easy to maintain. It provides developers options to write client-side application in a clean Model View Controller (MVC) architecture. AngularJS automatically handles JavaScript code suitable for different browsers and so, the developer does not have to make his JavaScript application cross-browser compliant.

Building blocks of AngularJS:

Controller – JavaScript functions that are bound to a particular scope.

Scope – Objects that refer to the model. They act as a glue between controller and view.

Directives – Markers on DOM elements, these can be used to create custom HTML tags that serve as new, custom widgets. AngularJS has built-in directives (ngBind, ngModel, ngBind, etc.)

Data-binding – It is the automatic synchronization of data between model and view components.

Services – AngularJS come with several built-in services for example $http to make a XMLHttpRequests. These are singleton objects which are instantiated only once in an app.

Dependency Injection – AngularJS has a built-in dependency injection sub-system that helps the developer by making the application easier to develop, understand, and test.

In this blog, I will focus on Controller and Directives.

Controller

A Controller is a JavaScript object which contains attributes and functions. A Controller is defined using the AngularJS built-in directive ng-controller.  A Controller handles all the operations related to a view to which it has been associated.

A Controller is defined as follows:

angular.module('myApp', []).controller('myController', function($scope) {
 });

And the above controller can be declared as follows:

<div id="myDiv" ng-app="myApp" ng-controller="myController">
 ......
 </div>

Built-in Directives

As the name itself indicates, Directive is an indicator to the angular compiler. It directs the angular compiler that what to do when it comes across a Directive. AngularJS provides such built-in directives to ease the developer work. Some of the important directives necessary to build an AngularJS app are-

  • ng-app – This directive defines and links an AngularJS application to HTML.
  • ng-controller – This directive associates a controller to a view.
  • ng-model – This directive binds the values of AngularJS application data to HTML input controls.
  • ng-bind – This directive binds the AngularJS Application data to HTML tags.
  • ng-repeat – This directive is used to iterate through a list and generate elements dynamically.
  • There are many other built-in directives which you can refer from the AngularJS documentation as and how you come across different requirements.

Sample Application

Let’s build a sample application which will give you a clear picture about how AngularJS application works. And then I shall introduce you to other AngularJS features.

What do you need to build an AngularJS app?

All you need is AngularJS framework JavaScript file, which you can download from https://angularjs.org/ or simply include the following script tag in your application template.

<script src=”http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js”>

You can use any text editor to create a AngularJS application.

Step-1: Create a template

<div id="myDiv">
 <p>Type your name in the input field:</p>
 <p><input type="text"></p>
 <p>Hello <span></span></p>
 </div>

Step-2: Create a Module

<script>
 angular.module('myApp', []);
 </script>

Step-3: Create a Controller

<script>
 angular.module('myApp', []).controller('myCtrl', function($scope) {
 $scope.name = "";
 });
 </script>

Step-4: Update the HTML template to attach Module and Controller

<div id="myDiv" ng-app="myApp" ng-controller="myCtrl">
 <p>Type your name in the input field:</p>
 <p><input type="text" ng-model="name"></p>
 <p>Hello <span ng-bind="name"></span></p>
 </div>

Result

In the above example you can see $scope model variable “name” has been associated to an input box. As the user types a name in the input box the same value will be reflected below the input box. This is called two-way data binding. In two-way data binding a model value updated in controller will be reflected in the view automatically and vice-versa.

Custom Directives

Custom directives are used to extend the HTML functionality. Custom directives are defined using the “directive” function. A custom directive replaces an element to which it has been applied. Let’s understand this with an example.

I want to define a custom tag as follows, which has an attribute called “name”.

<employee name=””></employee>

To handle above custom tag a custom directive has to be written

var app = angular.module('myApp', []);
 app.directive('employee', function() {
 var directive = {};
 directive.template = "Employee: <b>{{ name }}</b> “;
 directive.scope = {
 name : "=name"
 }
 directive.compile = function(element, attributes) {
 element.css("background", "lightgreen");
 }
 return directive;
 });

Result

This directive will be called as soon as any employee element is encountered in the HTML, and that element will be replaced with the directive’s template wherein it displays the employee name in bold letter with a light green background color.

Don’t miss my next blog where I discuss Dependency and Injection Services!