Technical

Angular 2 – Let’s learn together!

 

Angular2 Overview

Angular2 Introduction

Angular2’s major advantage – One of the most confusing things for a UI developer who is from a JAVA background would be all about type in JavaScript. We know that, JS is not a strictly typed language. To avoid those kinds of confusions, Angular 2 is here with TypeScript.

TypeScript can be considered as a superset of JavaScript, it’s a typed JavaScript J To know more about TypeScript, please refer – http://www.typescriptlang.org/. We will not cover more on this here as we concentrate on AJS and will throw light on TS whenever required in between!

 Architecture Overview:

AJS2architecture

Good news is – we have class, encapsulation, import, export and everything now! 🙂

Let’s review the overall architectural components in AJS2 one by one. TypeScript is actually a modular programming language. So, it’s always the best practice to keep our Angular2 apps modular. So, we can consider that Angular is a collection of multiple modules. We can import and export one another as in Java. AJS has its own library modules in its core component/library.

Next, coming to major building blocks of AJS2 architecture, the following are very important components/building blocks/features:

  • Component
  • Template
  • Directive
  • Metadata / Decorators
  • Services

Also, as in earlier versions of Angular, we have Dependency Injection and Data Binding concepts too

Component: Angular Components are nothing but, the basic building block, where all our application business logic resides. It’s similar to the controllers we had in our AJS 1.x. It can be considered as a function or a kind of class as in Java. It has properties and methods and also, scope that we had in AJS 1.x is combined here in component.

Template: Angular templates are nothing but our application views. It’s more like a regular HTML which renders the DOM as per the instructions it receives from component or the directive.

Observe closely that, we have {{myName}}, which later evaluates to the actual name value that’s bound to the property myName during run time. So, we have {{…}} symbol to render the values.

Similarly, we also can have – event binding or can attach event handlers in our template using the syntax as below in the examples.

Earlier, to achieve the same goal, we had ng-click, ng-“event” specific handlers. Now, we have to attach handlers to the events by assigning them with a pair of parenthesis.

We can have two-way data binding using “ngModel”, where it’s a combination of handling events along with binding the properties as below, this can also be considered as one of the attribute directives.

Directives: We have two types of directives in Angular2, the structural and the attribute. Structural directives alter the DOM, whereas the attribute directives alter the behavior of an existing element on DOM, may be based on certain events as we have seen above in ngModel.

Note: We do not have ng-repeat. We use ngFor, ngIf etc with an asterisk symbol for structural directives. A component is also a directive, where it does have a template bound to it. We use something called as decorators – @ to write custom directives whenever necessary.

Metadata: Metadata tells angular how to utilize and compile the component. It briefs what to do with that particular component. In the example we can see that ‘selector’ and ‘template’ are the two metadata fields, which tells angular to compile “my-app” to this class and insert the DOM with the template given. Selector actually represents the simple CSS selector for the component, like a class selector of CSS 🙂

Service: Service can be anything like a web service or a function that provides the necessary information or input that our app needs. It can have getters and setters!

Related example snippets:

examples
Examples2

This is all about the high-level overview of AJS 2. Will dive deeper in the next series 🙂

Understanding the JavaScript Closures

Understanding the JavaScript Closures

What is a closure?

A closure is an inner function that has access to the outer/enclosing function’s variables scope chain.
Closure has three scope chains i.e.,
1) It has access to its own scope (variables defined between its curly brackets)
2) It has access to the outer function’s variables, and
3) It has access to the global variables.

The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters.

Note that the inner function cannot call the outer function’s arguments object; however, even though it can call the outer function’s param’s directly.

In simpler way to say what is closure? If you create a function inside / within another function its called as closure / private function.

Understanding the JavaScript Closures

An Example of Closures in JavaScript:

 

Will come up with next article on this with more details of closures and some more example’s & Closures’ Rules and Side Effects, usage and so on….
 
You can find more even in W3C about closures:
URL : http://www.w3schools.com/js/js_function_closures.asp

The Unified Secure IoT Framework

The Unified Secure IoT Framework

The Unified Secure IoT Framework: The next Generation Unified Secure Framework for Secure IoT – The Internet Of Things!

ABSTRACT

This post efforts to explain a unified security solution for the commonly observed threats in the field of Healthcare, Insurance and Payment during the implementation of connected solution as a part of the next frontiers in IoT.

1. INTRODUCTION

IoT is nothing but Internet of things. When we say IoT, it’s actually a set of connected things (especially devices, now everything including smart wears like a T-shirt). It’s soon going to be Internet of feelings, health or personal life as IoT includes devices that record health data of a user, his own house related information and control, which is usually termed as Connected Home. By 2020, the world will have thirty billion IoT Devices is one of the estimates given by IDC.

2. CURRENT TRENDS IN IoT

Healthcare Industry is seeing a major impact of IoT with the evolution of connected technologies and sensors, which help in measuring heart rate and track fitness. Nike, FitBit are some examples of fitness trackers. Apple and Google have their own health recording platforms namely, Apple HealthKit and Google Fit. These provide unified environment for user’s health record access on a handy mobile device which is simple and many health care organizations are coming up with various fitness apps with the help of APIs exposed by these platforms. Fashion brands are upcoming with technology trends like smart t- shirts, shirts for sportsmen, which help in measuring sportsmen’s activity (number of steps taken etc), analyze mood and track their fitness. Ralph Lauren has their own glimpse of the Polo Tech smart shirt, new wearable technology which reads activity (steps, how long the player is active), breathing and heart rate and delivers it all in real-time to a Bluetooth- connected smart phone. Google Glass is another example of smart wear technology.

Insurance Industry is adopting smart technology with the concept of Connected Home, Connected Health and Connected Cars for calculating premium, rewarding, risk assessment etc. Retail Industry is however implementing smart pay, credit card payment techniques, EMI offers, with the evolution of devices and sensors. Banking is another major sector which is adopting IoT concepts for smart payment, online purchase/payment etc.

3. COMMON SECURITY THREATS

So everything on the earth seems connected through Internet in one or the other way, be it an Insurance Industry, or any personal information like health record of a user. Now, the major concern in all these areas is Security and Privacy! How secure is the connection, process and data that’s being used by these IoT techniques?

3.1 Digital Payment

We know that credit card information is the most common information that a retail purchase will have access to, and it will not be difficult to get access to user’s personal information through credit card details. Making online payment is always through a secured gateway is what the websites claim but, user may not be aware of how secure really the system is.

3.2 Connected Home

When we say Connected Home, user can remotely control the door locks through his mobile device and sensors at his home refrigerators send constant data logs on usage, power consumption etc based on his customization. Home Inventory details may be captured in his own mobile device if he has any smart app installed to do so. Also, Apple is coming up with its indoor positioning system with which user will be able to track his own historical visits to different places, floor number, etc. Though Apple says its very much secure, we are unaware of man in the middle attack or what if the device is lost? How secure is the device and data stored in it?

3.3 Connected Health

Health related information may have direct access to user’s personal information (PII – Personally Identifiable Information), insurance details, credit card details, most importantly user’s biometric and health information which is very private. Also, digital data dispose is another head ache when the users block their credit card during fraud or a hacker attack. Home security systems have alarms and web camera but, what about the connection privacy and secure access to these, though they are designed keeping in mind the safety of the house.

3.4 Social Share

Social media play a major role in data sharing. Many apps or many devices or solution offer social media connectivity and single sign on. This again raises question of user data privacy and security. Google’s Oauth authentication technique is being implemented in most of the authentication mechanisms. But, how easy it is for hackers to break this technique and get access to private data or cause vulnerabilities in different ways. This technique has been there since very old days and many programmers are capable of studying the pattern and finding the loop holes to break it. Apps like true caller have their own database where, anybody whose data is fed by any person to the true caller will be available publicly; raising a privacy concern. Though this app helps a lot in blocking unwanted calls, manage contacts list etc, it doesn’t ensure data security and privacy to an expected level.

4. UNIFIED SECURE FRAMEWORK

Industry is coming up with its own security framework, and techniques to prevent all these security threats and privacy concerns. One better technique will be Multiple Authentication with at least one being the biometric features like fingerprints or face recognition or retina scanning. A centralized control system can be implemented to monitor privacy and security in IoT. The centralized hub will provide access to complete IoT system for a single user. Industry can adopt this security framework, where in each registered user will be provided access to private data and connectivity to his own connected devices.

Secure Framework
The Unified Secure Framework for IoT

4.1 Secure Authentication

When the user registers his device in the security framework, the framework should be capable of identifying and storing the unique device id like UUID (Universally Unique Identifier) or ASHWD (Application Specific Hardware Identifier) in an encrypted format. The same id will be used by the framework next time when there is a request from the same device to authenticate the device. Next, to identify that device is not stolen or authenticate the right user, the security framework can implement / provide app that authenticates the user using his biometric feature like face recognition. Once this is confirmed, the user will be redirected to the OAuth or any other authentication mechanism provided by the IoT apps. Be it Health Kit or Google Fit, everybody should think of implementing such two-way or multiple authentication technique and encryption and decryption mechanism for data transfer.

4.2 Secure Data Transfer

This security framework will be a layer on top of app-level security implementation techniques. Still, the concern regarding privacy in case of credit card based retail purchase remains. This can be prevented by implementation of this security framework in the payment gateway as well. The framework should enable purchase with data being shared only between the retailer and the consumer. The communication channel should have completely encrypted data transfer and it should be identified with a biometric feature. The credit card number should be stored in encrypted format in the retailer’s firm using this security framework and whenever there is request to retail purchase, the payment should pass through this gateway and identify user using his face recognition and immediately a secure PIN should also be sent to user’s mobile device for second level authentication. Once the user enters the PIN, the secured framework will authenticate the device in the same way as discussed above. We can expect the card manufacturers too to implement such technique soon, which will make this easier.

4.3 Secured Analytics Engine

Sharing of data in social media must be restricted based on user’s permission. Access level should also be restricted for each app. The security framework should implement a constant polling or a technique to ensure secure data sharing and reserve privacy of users in the media by running a script once in a month/week to ensure the secure access and privacy protection. This should be customized according to the user’s needs. e.g. If a user has any concern on his privacy he can request the framework to run the script and make use of analytics, which can detect any security threat. The analytics engine is part of this security framework, which will be constantly studying the usage pattern and analyze the user behavior on his IoT connectivity pattern or statistics. So, this analysis will also contribute towards identifying the threat.

5. POWER CRISIS

Connected Things via Solar Power
Solar Powered IoT

Another upcoming major challenge in IoT is power management. We know that, power is the main means of connectivity in IoT. For IoT, we need connectivity and that connectivity is through Bluetooth, WiFi or any mobile networks. Bluetooth low energy or Bluetooth LE is the latest trend in Bluetooth technology, which is the future of Bluetooth. It’s marketed as Bluetooth Smart. Wi-Fi Direct is a P2P standard for devices to transfer data without being connected to the same Wi- Fi network. But, we all know that, all these consume battery power of the device. And, mobile device usage is based on power consumption. Power management is critical in case of sensors and connected devices. So, we need to think in terms of power management in IoT.

6. RENEWABLE ENERGY SOURCE – THE SOLAR POWER

Solar power is available in plenty on the planet which can be utilised as a source of power. We can install a solar power panel for energy storage in the IoT hub and utilise the same for power during connectivity. Innovation and invention should be carried out in sensors and areas of solar energy utilisation for the same as soon as possible.

7. CONCLUSION

Security, privacy and power management are going to be the biggest challenges in the next frontier IoT. It is always good to be prepared for the future rather than worrying later about the issue. Implementation of secured framework and a proper power management plan at the early stage helps in identifying the risks, and pros and cons of the implemented technology for further improvements. This stabilizes the solution when there is a huge need for the same soon.

8. ACKNOWLEDGMENTS

This post was posted to TCS as a part of TCS ‘ call for paper on IoT Security and Privacy. I would like to thank for the opportunity to TCS.

I would like to improve this Solution with more ideas flooding in and “Unified Secure Framework” need to be improved a lot with concrete solution. So suggestions and ideas are welcome in this regard.

HTML5 Web Speech API

HTML5 Web Speech API

Good news for all those who have been waiting for speech recognition and synthesis. HTML5 has published it’s draft specification on – Web Speech API for speech recognition by browser. Many of you must have already experienced this in your mobile device – Voice Search!

HTML5 Web Speech API has 2 parts :

Speech Recognition: This part of the API helps in identifying or recognising the user’s voice or speech.
Speech Synthesis: This part helps in synthesising the recognised voice and convert it to text. Speech to text synthesis.

Latest version of Chrome (above 40), chrome for android and iOS 7.1 have partial support for the API at present. You can still get the latest updates on browser support from – here!

This requires an Internet connection as this is implemented in such a way that the speech recognition and synthesis happen at Google using it’s web services (where they have algorithms for this) and this may rise a security concern as sensitive data form filling can not be accomplished by this. But, we can write our own web services utilising this Speech API(TBD:How Exactly to do this?). HTML5 offline support may be another soon to be implemented option.

At present, android supports offline voice search with its own settings, and Android APIs/offline library as explained  here!

Please share your experience if you could access the API offline, without setting the offline settings for Android.

Please read details here:

WURFL js – Decision Made Easier?

WURFL js – Decision Made Easier? :

Mobile world is still in confusion about making a decision on – device detection – whether it should be done at client-side or should we move it to server-side, and in turn about the presentation logic?

In server-side identification, when a request is made from a particular device, be it a smartphone or a tablet or anything else, the request header was processed first to check the user agent (UA). Techniques using WURFL () are very popular in this area.

In client-side device detection, when a request is made, a feature detection is enabled to identify the type of device. CSS media-queries are most popular technique used in this case.

Each of these have their own pros and cons. It depends on many factors like business requirement, cost, effort, security, support for modern technologies like HTML5 features, scalability, maintainability, performance etc and etc!

WURFL.js is a new introduction to this world from the traditional WURFL team. It helps you to detect the type of device by including a JavaScript file (WURFL.js) to your client side HTML page and process or render the pages accordingly.

Confused? Just go to – http://web.wurfl.io and do a “View Source” from your smartphone and the desktop! You will get the right answer to all your questions in a minute!

Only practical implementation and success stories would help us in judging the pros and cons of this technique. Have you tried this?

More Here:

AngularJS the MVVM way better modular UI Development

AngularJS the MVVM way better modular UI Development

Lot of buzz about Plug and Play and design patterns in the UI development round the clock!
Plug and Play is possible with good architecture and adoption of good design pattern. Most popular are – MVC, MVP and MVVM. Most of us are familiar with MVC (Model-View-Controller), MVP (Model-View-Presentation) and the one picking up now is – MVVM.

MVVM (Model-View-ViewModel) is actually an architectural pattern used in software engineering that originated from Microsoft as a specialization of the Presentation Model design pattern introduced by Martin Fowler. For those who want to understand more on – MVC, MVP, can refer to http://www.codeproject.com/Articles/288928/Differences-between-MVC-and-MVP-for-Beginners and also MVVM included here – http://www.codeproject.com/Articles/66585/Comparison-of-Architecture-presentation-patterns-M.

The above details are all specific to the design pattern. So let’s now understand how we can adopt to this (MVVM) good pattern in UI development, especially, the Hybrid App development projects.

MVVM components include:
1. Model
2. View
3. View Model
Here, the controller of MVC is replaced by a ViewModel and the View Model is a JavaScript function which acts as a model for the view and is responsible for maintaining relationship between view and the model. If we update anything in view, it gets updated in model, change anything in model, it reflects in the view, and it’s called 2-way data binding. MVVM separates business logic from UI using the ViewModel. AngularJs helps in achieving this using plain JavaScript objects. $scope is the important object in AJS (AngularJS), which allows defining both the data and methods that will be available for the view.
Let’s look into the details of MVVM AJS:
Model:
Holds application/domain specific data along with actual information what our app needs to deal with. Eg: user name, age, DOB etc. in a form.
Services or Factories can be used to handle Model in AJS.
Services are view- control logic handlers as well. We can call it as a View-Model interface (or a VM Interface), where all the common business logic reside. This helps in easy plug and play of two dependent modules.
View:
View handles the events, behaviour and actual UI representation.
Eg: A visual representation of a Submit button, button click behaviour etc. The behaviour is actually handled by ViewModel. Eg: On click of a submit button, AJAX Post may be performed and data is posted to server etc (handled by ViewModel); and a pop-up message for success or
failure should be shown up (View).
Angular templates (using directives) act as the Views in AJS Hybrid apps.

ViewModel:
Holds the presentation logic and interacts with Model on state changes. Example is discussed in the View details above.

AJS Controllers serve this purpose in Hybrid apps. An AJS controller (the ViewModel) should –

• Include the state of the presentation – like which item is selected using radio button, if a switch is turned on/off etc.
• Utilize and process data from Model/Server – fetch DB, make a post / get AJAX request and pre-process data if required, before presenting.
• Be able to communicate with other Controllers via methods/interfaces.

This is all about AJS MVVM insights. 🙂

Please find the detailed tutorials on AJS here for more information:
http://zaiste.net/2013/07/concisely_how_to_get_started_with_angularjs/
http://codechutney.in/blog/javascript/mvc-and-mvvm-with-angularjs/
https://www.safaribooksonline.com/library/view/angularjs-up-and/9781491901939/ch01.html
https://angularjs.org/ (Official AJS site).
Disclaimer:

• This article is intended to explain the idea of MVVM design pattern using AJS in Hybrid apps. This will not give any in-depth details of neither MVVM nor AJS.
• AJS can be done in MVC as well.
• MVC handled in a better way is also a good candidate that supports Modularity, and Plug and Play. MVVM enforces MVC in a better modular approach.

All about hammer.js a start to touch gestures and multitouch

All about hammer.js a start to touch gestures and multitouch

Hammer is a open-source JavaScript Library for adding touch gestures support that can recognize gestures made by touch, mouse and pointerEvents to any website so that users can interact with them easier on touch devices. It doesn’t have any dependencies, and it’s small, only 3.71 kB minified + gzipped!

It supports tap, double tap, press, hold, drag, horizontal pan and swipe and the multi-touch pinch and rotate recognizers and also transform.

Getting Started

What’s new in 2.0?

It’s completely rewritten, with reusable gesture recognizers, and improved support for the recent mobile browsers by making use of the touch-action css property when possible. Also support for multiple Hammer instances the same time, so multi-user became possible.


Usage

It’s easy to use, just include the library and create a new instance.

var hammertime = new Hammer(myElement, myOptions);
hammertime.on('pan', function(ev) {
    console.log(ev);
});

By default it adds a set of tap, doubletap, press, horizontal pan and swipe, and the multi-touch pinch and rotate recognizers. The pinch and rotate recognizers are disabled by default because they would make the element blocking, but you can enable them by calling:

hammertime.get('pinch').set({ enable: true });
hammertime.get('rotate').set({ enable: true });

Enabling vertical or all directions for the pan and swipe recognizers:

hammertime.get('pan').set({ direction: Hammer.DIRECTION_ALL });
hammertime.get('swipe').set({ direction: Hammer.DIRECTION_VERTICAL });

Also the viewport meta tag is recommended, it gives more control back to the webpage by disableing the doubletap/pinch zoom. More recent browsers that support the touch-action property don’t require this.

<meta name="viewport" content="user-scalable=no, width=device-width,
 initial-scale=1, maximum-scale=1">

More control

You can setup your own set of recognizers for your instance. This requires a bit more code, but it gives you more control about the gestures that are being recognized.

var mc = new Hammer.Manager(myElement, myOptions);

mc.add( new Hammer.Pan({ direction: Hammer.DIRECTION_ALL, threshold: 0 }) );
mc.add( new Hammer.Tap({ event: 'quadrupletap', taps: 4 }) );

mc.on("pan", handlePan);
mc.on("quadrupletap", handleTaps);

The example above creates an instance containing a pan and a quadrupletap gesture. The recognizer instances you create a being executed in the order they are added, and only one can be recognized at the time.

Simultaneous recognizing

If you want to recognize two gestures simultaneously, you can use the the recognizeWith() method. The example below does this with the pinch and rotate recognizers, which will improve usability.

var pinch = new Hammer.Pinch();
var rotate = new Hammer.Rotation();
pinch.recognizeWith(rotate);

Now Hammer is able to run pinch and rotate the same time. You can also separate them with the dropRecognizeWith() method on the recognizer instance.

Require failure of an other recognizer

With the method requireFailure() you can let a recognizer require the failure of an other recognizer before recognizing. This could become useful when you want to nest two gestures, like pan-horizontal and pan-vertical. Removing the dependency could be done with the dropRequireFailure() method.

var horizontal = new Hammer.Pan({
    event: 'panh',
    direction: Hammer.DIRECTION_HORIZONTAL
});
var vertical = new Hammer.Pan({
    event: 'panv',
    direction: Hammer.DIRECTION_VERTICAL
});
vertical.requireFailure(horizontal);

Using requireFailure to recognize multiple taps

Because multiple gestures can be recognized simultaneously and a gesture can be recognized based on the failure of other gestures. Multiple taps on the same element can be easily recognized on this way:

var hammer = new Hammer(el, {});

var tap = new Hammer.Tap();
var doubleTap = new Hammer.Tap({event: 'doubleTap', taps: 2 });
var tripleTap = new Hammer.Tap({event: 'tripleTap', taps: 3 });

hammer.add([tripleTap, doubleTap, tap]);

tripleTap.recognizeWith([doubleTap, tap]);
doubleTap.recognizeWith(tap);

doubleTap.requireFailure(tripleTap);
tap.requireFailure([tripleTap, doubleTap]);

When a tap gesture requires a failure to be recognized, its recognizer will wait a short period to check that the other gesture has been failed. In this case, you should not assume that its tap gesture event will be fired immediately.

Tips ‘n Tricks

Try to avoid vertical pan/swipe

Vertical panning is used to scroll your page, and some (older) browsers don’t send events so Hammer isn’t able to recognize these gestures. An option would be to provide an alternative way to do the same action.

Test on a real device

Sometimes Hammer just needs some fine-tuning, like the swipe velocity or some other thresholds. Also, for better performance on slower devices your should try to keep you callbacks as simple as possible.

Remove tap highlight on Windows Phone

IE10 and IE11 on Windows Phone have a small tap highlight when you tap an element. Adding this meta tag removes this.

<meta name="msapplication-tap-highlight" content="no" />

“I can’t select my text anymore!”

Hammer is setting a property to improve the UX of the panning on desktop. Regularly, the desktop browser would select the text while you drag over the page. The user-select css property disables this.

If you care about the text-selection and not so much about the desktop experience, you can simply remove this option from the defaults. Make sure you do this before creating an instance.

delete Hammer.defaults.cssProps.userSelect;


Browser/device support

Don’t worry if your browser or OS isn’t listed, it might work anyway! Internet Explorer 8 and older aren’t supported.

Browsers that have native support for touch-action might have an improved experience then the browsers that don’t.

Browser Pan Pinch Press Rotate Swipe Tap Multi-user Touch-action
Windows Phone 8 – IE10
Android 2.3 – browser
Android 2.3 – FireFox
Android 4.x – browser
Android 4.4 – browser
Android 4 – Chrome
Android 4 – Opera ?
Android 4 – FireFox
Android 4 w/ mouse n/a
iOS 6
iOS 7
BlackBerry 10 ? ?
FireFox OS (simulator) ? ?
Desktop – IE11
Desktop – IE10
Desktop – IE9
Desktop – Chrome
Desktop – Firefox
Desktop – Opera ?
Chromebook ?
Windows 8 /w pen n/a
Windows 8 /w touch n/a
Windows 8 /w mouse n/a
Windows 8 /w mixed n/a

backbone.js tutorial a walk through

backbone.js tutorial

BACKBONE.JS

Why do you need Backbone.js?

Building single-page web apps or complicated user interfaces will get extremely difficult by simply using jQuery or MooTools. The problem is standard JavaScript libraries are great at what they do – and without realizing it you can build an entire application without any formal structure. You will with ease turn your application into a nested pile of jQuery callbacks, all tied to concrete DOM elements.

I shouldn’t need to explain why building something without any structure is a bad idea. Of course you can always invent your own way of structuring your application but you miss out on the benefits of the open source community.

Why single page applications are the future

Backbone.js enforces that communication to the server should be done entirely through a RESTful API. The web is currently trending such that all data/content will be exposed through an API. This is because the browser is no longer the only client, we now have mobile devices, tablet devices, Google Goggles and electronic fridges etc.

So how does Backbone.js help?

Backbone is an incredibly small library for the amount of functionality and structure it gives you. It is essentially MVC for the client and allows you to make your code modular. If you read through some of the beginner tutorials the benefits will soon become self evident and due to Backbone.js light nature you can incrementally include it in any current or future projects.

What is a model?

Across the internet the definition of MVC is so diluted that it’s hard to tell what exactly your model should be doing. The authors of backbone.js have quite a clear definition of what they believe the model represents in backbone.js.

Models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control.

So for the purpose of the tutorial let’s create a model.

    Person = Backbone.Model.extend({
        initialize: function(){
            alert("Welcome to this world");
        }
    });

    var person = new Person;

So initialize() is triggered whenever you create a new instance of a model( models, collections and views work the same way ). You don’t have to include it in your model declaration but you will find yourself using it more often than not.

Setting attributes

Now we want to pass some parameters when we create an instance of our model.

    Person = Backbone.Model.extend({
        initialize: function(){
            alert("Welcome to this world");
        }
    });

    var person = new Person({ name: "Thomas", age: 67});
    // or we can set afterwards, these operations are equivelent
    var person = new Person();
    person.set({ name: "Thomas", age: 67});

So passing a JavaScript object to our constructor is the same as calling model.set(). Now that these models have attributes set we need to be able to retrieve them.

Getting attributes

Using the model.get() method we can access model properties at anytime.

    Person = Backbone.Model.extend({
        initialize: function(){
            alert("Welcome to this world");
        }
    });

    var person = new Person({ name: "Thomas", age: 67, child: 'Ryan'});

    var age = person.get("age"); // 67
    var name = person.get("name"); // "Thomas"
    var child = person.get("child"); // 'Ryan'

Setting model defaults

Sometimes you will want your model to contain default values. This can easily be accomplished by setting a property name ‘defaults’ in your model declaration.

    Person = Backbone.Model.extend({
        defaults: {
            name: 'Fetus',
            age: 0,
            child: ''
        },
        initialize: function(){
            alert("Welcome to this world");
        }
    });

    var person = new Person({ name: "Thomas", age: 67, child: 'Ryan'});

    var age = person.get("age"); // 67
    var name = person.get("name"); // "Thomas"
    var child = person.get("child"); // 'Ryan'

Manipulating model attributes

Models can contain as many custom methods as you like to manipulate attributes. By default all methods are public.

    Person = Backbone.Model.extend({
        defaults: {
            name: 'Fetus',
            age: 0,
            child: ''
        },
        initialize: function(){
            alert("Welcome to this world");
        },
        adopt: function( newChildsName ){
            this.set({ child: newChildsName });
        }
    });

    var person = new Person({ name: "Thomas", age: 67, child: 'Ryan'});
    person.adopt('John Resig');
    var child = person.get("child"); // 'John Resig'

So we can implement methods to get/set and perform other calculations using attributes from our model at any time.

Listening for changes to the model

Now onto one of the more useful parts of using a library such as backbone. All attributes of a model can have listeners bound to them to detect changes to their values. In our initialize function we are going to bind a function call everytime we change the value of our attribute. In this case if the name of our “person” changes we will alert their new name.

    Person = Backbone.Model.extend({
        defaults: {
            name: 'Fetus',
            age: 0
        },
        initialize: function(){
            alert("Welcome to this world");
            this.on("change:name", function(model){
                var name = model.get("name"); // 'Stewie Griffin'
                alert("Changed my name to " + name );
            });
        }
    });

    var person = new Person({ name: "Thomas", age: 67});
    person.set({name: 'Stewie Griffin'}); // This triggers a change and will alert()

So we can bind the change listener to individual attributes or if we like simply ‘this.on(“change”, function(model){});‘ to listen for changes to all attributes of the model.

Interacting with the server

Models are used to represent data from your server and actions you perform on them will be translated to RESTful operations.

The id attribute of a model identifies how to find it on the database usually mapping to the surrogate key.

For the purpose of this tutorial imagine that we have a mysql table called Users with the columns idnameemail.

The server has implemented a RESTful URL /user which allows us to interact with it.

Our model definition shall thus look like;

    var UserModel = Backbone.Model.extend({
        urlRoot: '/user',
        defaults: {
            name: '',
            email: ''
        }

    });

Creating a new model

If we wish to create a new user on the server then we will instantiate a new UserModel and call save. If the id attribute of the model is null, Backbone.js will send a POST request to the urlRoot of the server.

    var UserModel = Backbone.Model.extend({
        urlRoot: '/user',
        defaults: {
            name: '',
            email: ''
        }
    });
    var user = new Usermodel();
    // Notice that we haven't set an `id`
    var userDetails = {
        name: 'Thomas',
        email: 'thomasalwyndavis@gmail.com'
    };
    // Because we have not set a `id` the server will call
    // POST /user with a payload of {name:'Thomas', email: 'thomasalwyndavis@gmail.com'}
    // The server should save the data and return a response containing the new `id`
    user.save(userDetails, {
        success: function (user) {
            alert(user.toJSON());
        }
    })

Our table should now have the values

1, ‘Thomas’, ‘thomasalwyndavis@gmail.com’

Getting a model

Now that we have saved a new user model, we can retrieve it from the server. We know that the id is 1 from the above example.

If we instantiate a model with an id, Backbone.js will automatically perform a get request to the urlRoot + ‘/id’ (conforming to RESTful conventions)

    // Here we have set the `id` of the model
    var user = new Usermodel({id: 1});

    // The fetch below will perform GET /user/1
    // The server should return the id, name and email from the database
    user.fetch({
        success: function (user) {
            alert(user.toJSON());
        }
    })

Updating a model

Now that we have a model that exist on the server we can perform an update using a PUT request. We will use the save api call which is intelligent and will send a PUT request instead of a POST request if an id is present(conforming to RESTful conventions)

    // Here we have set the `id` of the model
    var user = new Usermodel({
        id: 1,
        name: 'Thomas',
        email: 'thomasalwyndavis@gmail.com'
    });

    // Let's change the name and update the server
    // Because there is `id` present, Backbone.js will fire
    // PUT /user/1 with a payload of `{name: 'Davis', email: 'thomasalwyndavis@gmail.com'}`
    user.save({name: 'Davis'}, {
        success: function (model) {
            alert(user.toJSON());
        }
    });

Deleting a model

When a model has an id we know that it exist on the server, so if we wish to remove it from the server we can call destroydestroy will fire off a DELETE /user/id (conforming to RESTful conventions).

    // Here we have set the `id` of the model
    var user = new Usermodel({
        id: 1,
        name: 'Thomas',
        email: 'thomasalwyndavis@gmail.com'
    });

    // Because there is `id` present, Backbone.js will fire
    // DELETE /user/1 
    user.destroy({
        success: function () {
            alert('Destroyed');
        }
    });

Tips and Tricks

Get all the current attributes

      
    var person = new Person({ name: "Thomas", age: 67});
    var attributes = person.toJSON(); // { name: "Thomas", age: 67}
    /* This simply returns a copy of the current attributes. */

    var attributes = person.attributes;
    /* The line above gives a direct reference to the attributes and you should be careful when playing with it.   Best practise would suggest that you use .set() to edit attributes of a model to take advantage of backbone listeners. */

Validate data before you set or save it

    Person = Backbone.Model.extend({
        // If you return a string from the validate function,
        // Backbone will throw an error
        validate: function( attributes ){
            if( attributes.age < 0 && attributes.name != "Dr Manhatten" ){
                return "You can't be negative years old";
            }
        },
        initialize: function(){
            alert("Welcome to this world");
            this.bind("error", function(model, error){
                // We have received an error, log it, alert it or forget it :)
                alert( error );
            });
        }
    });

    var person = new Person;
    person.set({ name: "Mary Poppins", age: -1 }); 
    // Will trigger an alert outputting the error

    var person = new Person;
    person.set({ name: "Dr Manhatten", age: -1 });
    // God have mercy on our souls

What is a view?

Backbone views are used to reflect what your applications’ data models look like. They are also used to listen to events and react accordingly. This tutorial will not be addressing how to bind models and collections to views but will focus on view functionality and how to use views with a JavaScript templating library, specifically Underscore.js’s _.template.

We will be using jQuery 1.8.2 as our DOM manipulator. It’s possible to use other libraries such as MooTools or Sizzle, but official Backbone.js documentation endorses jQuery. Backbone.View events may not work with other libraries other than jQuery.

For the purposes of this demonstration, we will be implementing a search box. A live example can be found on jsFiddle.

    SearchView = Backbone.View.extend({
        initialize: function(){
            alert("Alerts suck.");
        }
    });

    // The initialize function is always called when instantiating a Backbone View.
    // Consider it the constructor of the class.
    var search_view = new SearchView();

The “el” property

The “el” property references the DOM object created in the browser. Every Backbone.js view has an “el” property, and if it not defined, Backbone.js will construct its own, which is an empty div element.

Let us set our view’s “el” property to div#search_container, effectively making Backbone.View the owner of the DOM element.

<div id="search_container"></div>

<script type="text/javascript">
    SearchView = Backbone.View.extend({
        initialize: function(){
            alert("Alerts suck.");
        }
    });

    var search_view = new SearchView({ el: $("#search_container") });
</script>

Note: Keep in mind that this binds the container element. Any events we trigger must be in this element.

Loading a template

Backbone.js is dependent on Underscore.js, which includes its own micro-templating solution. Refer to Underscore.js’s documentation for more information.

Let us implement a “render()” function and call it when the view is initialized. The “render()” function will load our template into the view’s “el” property using jQuery.

<script type="text/template" id="search_template">
  <label>Search</label>
  <input type="text" id="search_input" />
  <input type="button" id="search_button" value="Search" />
</script>

<div id="search_container"></div>

<script type="text/javascript">
    SearchView = Backbone.View.extend({
        initialize: function(){
            this.render();
        },
        render: function(){
            // Compile the template using underscore
            var template = _.template( $("#search_template").html(), {} );
            // Load the compiled HTML into the Backbone "el"
            this.$el.html( template );
        }
    });

    var search_view = new SearchView({ el: $("#search_container") });
</script>

Tip: Place all your templates in a file and serve them from a CDN. This ensures your users will always have your application cached.

Listening for events

To attach a listener to our view, we use the “events” attribute of Backbone.View. Remember that event listeners can only be attached to child elements of the “el” property. Let us attach a “click” listener to our button.

<script type="text/template" id="search_template">
  <label>Search</label>
  <input type="text" id="search_input" />
  <input type="button" id="search_button" value="Search" />
</script>

<div id="search_container"></div>

<script type="text/javascript">
    SearchView = Backbone.View.extend({
        initialize: function(){
            this.render();
        },
        render: function(){
            var template = _.template( $("#search_template").html(), {} );
            this.$el.html( template );
        },
        events: {
            "click input[type=button]": "doSearch"
        },
        doSearch: function( event ){
            // Button clicked, you can access the element that was clicked with event.currentTarget
            alert( "Search for " + $("#search_input").val() );
        }
    });

    var search_view = new SearchView({ el: $("#search_container") });
</script>

Tips and Tricks

Using template variables

<script type="text/template" id="search_template">
    <!-- Access template variables with <%= %> -->
    <label><%= search_label %></label>
    <input type="text" id="search_input" />
    <input type="button" id="search_button" value="Search" />
</script>

<div id="search_container"></div>

<script type="text/javascript">
     SearchView = Backbone.View.extend({
        initialize: function(){
            this.render();
        },
        render: function(){
            //Pass variables in using Underscore.js Template
            var variables = { search_label: "My Search" };
            // Compile the template using underscore
            var template = _.template( $("#search_template").html(), variables );
            // Load the compiled HTML into the Backbone "el"
            this.$el.html( template );
        },
        events: {
            "click input[type=button]": "doSearch"  
        },
        doSearch: function( event ){
            // Button clicked, you can access the element that was clicked with event.currentTarget
            alert( "Search for " + $("#search_input").val() );
        }
    });

    var search_view = new SearchView({ el: $("#search_container") });
</script>

What is a router?

Backbone routers are used for routing your applications URL’s when using hash tags(#). In the traditional MVC sense they don’t necessarily fit the semantics and if you have read “What is a view?” it will elaborate on this point. Though a Backbone “router” is still very useful for any application/feature that needs URL routing/history capabilities.

Defined routers should always contain at least one route and a function to map the particular route to. In the example below we are going to define a route that is always called.

Also note that routes interpret anything after “#” tag in the URL. All links in your application should target “#/action” or “#action”. (Appending a forward slash after the hashtag looks a bit nicer e.g. http://example.com/#/user/help)

<script>
    var AppRouter = Backbone.Router.extend({
        routes: {
            "*actions": "defaultRoute" // matches http://example.com/#anything-here
        }
    });
    // Initiate the router
    var app_router = new AppRouter;

    app_router.on('route:defaultRoute', function(actions) {
        alert(actions);
    })

    // Start Backbone history a necessary step for bookmarkable URL's
    Backbone.history.start();

</script>

Dynamic Routing

Most conventional frameworks allow you to define routes that contain a mix of static and dynamic route parameters. For example you might want to retrieve a post with a variable id with a friendly URL string. Such that your URL would look like “http://example.com/#/posts/12”. Once this route was activated you would want to access the id given in the URL string. This example is implemented below.

<script>
    var AppRouter = Backbone.Router.extend({
        routes: {
            "posts/:id": "getPost",
            "*actions": "defaultRoute" // Backbone will try match the route above first
        }
    });
    // Instantiate the router
    var app_router = new AppRouter;
    app_router.on('route:getPost', function (id) {
        // Note the variable in the route definition being passed in here
        alert( "Get post number " + id );   
    });
    app_router.on('route:defaultRoute', function (actions) {
        alert( actions ); 
    });
    // Start Backbone history a necessary step for bookmarkable URL's
    Backbone.history.start();

</script>

Dynamic Routing Cont. “:params” and “*splats”

Backbone uses two styles of variables when implementing routes. First there are “:params” which match any URL components between slashes. Then there are “splats” which match any number of URL components. Note that due to the nature of a “splat” it will always be the last variable in your URL as it will match any and all components.

Any “*splats” or “:params” in route definitions are passed as arguments (in respective order) to the associated function. A route defined as “/:route/:action” will pass 2 variables (“route” and “action”) to the callback function. (If this is confusing please post a comment and I will try articulate it better)

Here are some examples of using “:params” and “*splats”

        routes: {

            "posts/:id": "getPost",
            // <a href="http://example.com/#/posts/121">Example</a>

            "download/*path": "downloadFile",
            // <a href="http://example.com/#/download/user/images/hey.gif">Download</a>

            ":route/:action": "loadView",
            // <a href="http://example.com/#/dashboard/graph">Load Route/Action View</a>

        },

        app_router.on('route:getPost', function( id ){ 
            alert(id); // 121 
        });
        app_router.on('route:downloadFile', function( path ){ 
            alert(path); // user/images/hey.gif 
        });
        app_router.on('route:loadView', function( route, action ){ 
            alert(route + "_" + action); // dashboard_graph 
        });

Routes are quite powerful and in an ideal world your application should never contain too many. If you need to implement hash tags with SEO in mind, do a google search for “google seo hashbangs”. Also check out Seo Server

What is a collection?

Backbone collections are simply an ordered set of models. Such that it can be used in situations such as;

  • Model: Student, Collection: ClassStudents
  • Model: Todo Item, Collection: Todo List
  • Model: Animal, Collection: Zoo

Typically your collection will only use one type of model but models themselves are not limited to a type of collection;

  • Model: Student, Collection: Gym Class
  • Model: Student, Collection: Art Class
  • Model: Student, Collection: English Class

Here is a generic Model/Collection example.

  var Song = Backbone.Model.extend({
      initialize: function(){
          console.log("Music is the answer");
      }
  });

  var Album = Backbone.Collection.extend({
    model: Song
  });

Building a collection

Now we are going to populate a collection with some useful data.

    var Song = Backbone.Model.extend({
        defaults: {
            name: "Not specified",
            artist: "Not specified"
        },
        initialize: function(){
            console.log("Music is the answer");
        }
    });

    var Album = Backbone.Collection.extend({
        model: Song
    });

    var song1 = new Song({ name: "How Bizarre", artist: "OMC" });
    var song2 = new Song({ name: "Sexual Healing", artist: "Marvin Gaye" });
    var song3 = new Song({ name: "Talk It Over In Bed", artist: "OMC" });

    var myAlbum = new Album([ song1, song2, song3]);
    console.log( myAlbum.models ); // [song1, song2, song3]

Introduction to LESS and Comparison to Sass

Introduction to LESS and Comparison to Sass

I’ve been using LESS ever since I stumbled upon it. CSS was never really a problem for me, in and of itself, but I was intrigued by the idea of using variables to create something along the lines of a color palette for my websites and themes.
less

As it turns out, LESS — and Sass for that matter — are so much more than that. LESS and Sass share a lot of similarities in syntax, including the following:

  • Mixins – Classes for classes.
  • Parametric mixins – Classes to which you can pass parameters, like functions.
  • Nested Rules – Classes within classes, which cut down on repetitive code.
  • Operations – Math within CSS.
  • Color functions – Edit your colors.
  • Namespaces – Groups of styles that can be called by references.
  • Scope – Make local changes to styles.
  • JavaScript evaluation – JavaScript expressions evaluated in CSS.

The main difference between LESS and Sass is the way in which they are processed. LESS is a JavaScript library and is, therefore, processed client-side.

Sass, on the other hand, runs on Ruby and is processed server-side. A lot of developers might not choose LESS because of the additional time needed for the JavaScript engine to process the code and output the modified CSS to the browser. There are a few ways around this. The way I get around it is to use LESS only during the development process. Once I’m finished, I copy and paste the LESS output into a minifier and then into a separate CSS file to be included in place of the LESS files. Another option is to use LESS.app to compile and minify your LESS files. Both options will minimize the footprint of your styles, as well as avoid any problems that might result from the client’s browser not running JavaScript. While this is not likely, it’s always a possibility.

Once you have Sass installed you can compile Sass locally into CSS and ship the code with your project.

LESS Is More

Installation

Including LESS in something that you’re building is about as easy as it gets:

  1. Go get yourself a copy of less.js;
  2. Create a file to put your styles in, such as style.less;
  3. Add the following code to your HTML’s <head>:
<link rel="stylesheet/less" type="text/css" href="styles.less">
<script src="less.js" type="text/javascript"></script>

Note the rel attribute of the link. You are required to append the /less to the end of the value in order for LESS to work. You are also required to include the script immediately after the link to the style sheet. If you’re using HTML5 syntax, and I can’t imagine why you wouldn’t be, you can leave out the type="text/css" and the type="text/javascript".

There’s also a server-side version of LESS. The easiest way to install LESS on the server is with Node Package Manager (NPM).

Variables

If you’re a developer, variables are one of your best friends. In the event that you’ll be using information repeatedly (in this case, a color), setting it to a variable makes sense. This way, you guarantee yourself consistency and probably less scrolling about looking for a hex value to copy and paste. You can even do some fun little adding and subtracting of hex values that you want to render. Take this example:

@blue: #00c;
@light_blue: @blue + #333;
@dark_blue: @blue - #333;

If we apply these styles to three divs, we can see the gradated effect created by adding and subtracting the hex values to and from the original blue:

A screenshot illustrating the transition from 3 shades of blue
The transition from @light_blue to @blue to @dark_blue.

The only difference in variables between LESS and Sass is that, while LESS uses @, Sass uses $. There are some scope differences as well, which I’ll get to shortly.

Mixins

On occasion, we might create a style that’s intended to be used repeatedly throughout the style sheet. Nothing is stopping you from applying multiple classes to the elements in the HTML, but you could also do this without ever leaving your style sheet, using LESS. To illustrate this, I have pasted some sample code that one might use to style two elements on the page.

.border {
border-top: 1px dotted #333;
}

article.post {
background: #eee;
.border;
}

ul.menu {
background: #ccc;
.border;
}

This will give you something similar to what you would get if you had gone back to the HTML file and added the .bordered class to the two elements there — except you’ve done it without leaving the style sheet. And it works just as well:

With Sass, you declare @mixin prior to the style to identify it as a mixin. Later, you declare @include to call it.

@mixin border {
border-top: 1px dotted #333;
}

article.post {
background: #eee;
@include border;
}

ul.menu {
background: #ccc;
@include border;
}

Parametric Mixins

Like having functions in your CSS, these can be immensely useful for those seemingly redundant tasks of modern-day CSS.
The best and most useful example of their use relates to the many vendor prefixes that we struggle with during this transition from CSS2 to CSS3.

Selector Inheritance

Here’s something not provided in LESS. With this ability, you can append a selector to a previously established selector without the need to add it in a comma-separated format.

.menu {
	border: 1px solid #ddd;
}

.footer {
	@extend .menu;
}

/* will render like so: */
.menu, .footer {
	border: 1px solid #ddd;
}

Nested Rules

Nesting classes and ids in CSS can be one of the only methods to keep your styles from interfering with and from being interfered with any other styles that may be added along the way. But this can get very messy. Using a selector like #site-body .post .post-header h2 is unappealing and takes up a lot of unnecessary space. With LESS, you can nest ids, classes and elements as you go. Using the example above, you could do something like this:

#site-body { …

    .post { …

        .post-header { …

            h2 { … }

            a { …

            	&:visited { … }
            	&:hover { … }
            }
        }
    }
}

The above code is essentially the same as the ugly selector in the previous paragraph, but it’s much easier to read and understand, and it takes up much less space. You can also refer in element styles to their pseudo-elements by using the &, which in this case functions similar to this in JavaScript.

Operations

This is about what you would expect: using fixed numbers or variables to perform mathematical operations in your styles.

@base_margin: 10px;
@double_margin: @base_margin * 2;

@full_page: 960px;
@half_page: @full_page / 2;
@quarter_page: (@full_page / 2) / 2;

For the record, I am aware that I could have also divided by four to get the @quarter_page variable, but I wanted to illustrate that the parentheses rule from the “order of operations” also applies. Parentheses are also required if you’re going to perform operations within compound properties; for example, border: (@width / 2) solid #000.

Sass is a lot more versatile with numbers than LESS. It has built into it conversion tables to combine comparable units. Sass can work with unrecognized units of measurement and print them out. This feature was apparently introduced in an attempt to future-proof the library against changes made by the W3C.

/* Sass */
2in + 3cm + 2pc = 3.514in

/* LESS */
2in + 3cm + 2pc = Error

Color Functions

Earlier, I mentioned how LESS helps me stick to a color scheme in my coding process. One of the parts that contributes to this the most is the color function. Suppose you use a standard blue throughout your styles, and you want to use this color for a gradated “Submit” button in a form. You could go into Photoshop or another editor to get the hex value for a slightly lighter or darker shade than the blue for the gradient. Or you could just use a color function in LESS.

@blue: #369;

.submit {
    padding: 5px 10px;
    border: 1px solid @blue;
    background: -moz-linear-gradient(top, lighten(@blue, 10%), @blue 100%); /*Moz*/
    background: -webkit-gradient(linear, center top, center bottom, from(lighten(@blue, 10%)), color-stop(100%, @blue)); /*Webkit*/
    background: -o-linear-gradient(top, lighten(@blue, 10%) 0%, @blue 100%); /*Opera*/
    background: -ms-linear-gradient(top, lighten(@blue, 10%) 0%, @blue 100%); /*IE 10+*/
    background: linear-gradient(top, lighten(@blue, 10%) 0%, @blue 100%); /*W3C*/
    color: #fff;
    text-shadow: 0 -1px 1px rgba(0,0,0,0.4);
}

The lighten function literally lightens the color by a percentage value. In this case, it will lighten the base blue by 10%. This method enables us to change the color of gradated elements and any other elements with that color simply by changing the base color itself. This could prove immensely helpful in theming. Plus, if you used a parametric function, like the ones listed above, you could alleviate some of that browser-prefix tedium with something as simple as .linear-gradient(lighten(@blue), @blue, 100%);.

Either way, you get an effect that’s rather nice:

Screenshot of a styled submit button
Our nicely gradated, variable-based “Submit” button.

There are a lot of other color functions for darkening and saturating colors and even spinning the color wheel to other colors. I recommend trying them out to see what you can come up with.

Sass seems to have a lot more color options — not that I would need them all. Lighten and darken are the only ones that I see myself using often.

Conditionals and Control

This is rather nifty, and another thing not provided by LESS. With Sass, you have the ability to use if { } else { } conditional statements, as well as for { } loops. It supports and, or and not, as well as the <, >, <=, >= and == operators.

/* Sample Sass "if" statement */
@if lightness($color) >; 30% {
  background-color: #000;
} @else {
  background-color: #fff;
}

/* Sample Sass "for" loop */
@for $i from 1px to 10px {
  .border-#{i} {
    border: $i solid blue;
  }
}

Namespaces

Namespaces can be used to add another level of organization to our CSS, by allowing us to create groups of commonly used styles and then pick from them along the way. For instance, if we created a group of styles called defaults, we could pull from this group when we come across an element that needs it.

#defaults {
	.nav_list () {
		list-style: none;
		margin: 0; padding: 0;
	}
	.button () { … }
	.quote () { … }
}

Later, in our code, if we come across a ul element within a nav element, we would know that we’ll need our default style. So, we can simply call it, and it will be applied.

nav ul {
	#defaults > .nav_list;
}

Scope

Scoping is standard throughout programming and thus standard in LESS. If you define a variable at the root level of your style sheet, it will be available and consistent throughout the document. If, however, you redefine the variable from within a selector such as an id or class, then it will be available — with the new value — only within that selector.

@color: #00c; /* blue */

#header {
	@color: #c00; /* red */

	border: 1px solid @color; /* will have a red border */
}

#footer {
	border: 1px solid @color; /* will have a blue border */
}

Because we’ve restated the variable within the #header selector, the value for that variable will be different and will apply only within that selector. Anything before or after it will retain the value of the original statement.

Scope is handled a little differently in Sass. In the above code, when the @color variable is changed to red, it will be interpreted as such from that point on within the code.

Comments

This part is pretty basic. Two types of comments are valid in LESS. The standard CSS comment, /* comment */, is valid and will get passed through the processing and outputted. Single-line comments, // comment, work as well but will not get passed and outputted and, as a result, are “silent.”

Importing

Importing is pretty standard, too. The standard @import: 'classes.less'; works just fine. If, however, you’re importing another LESS file, then the file extension is optional, so @import 'classes'; would work as well. If you want to import something without LESS processing it, you can use the .css extension (for example, @import: 'reset.css';).

String Interpolation

String values can also be used in variables and called within styles via @{name}.

@base_url = 'http://someurl.com';
background-image: url("@{base_url}/images/background.png");

Escaping

There will be times when you need to include a value that is not valid CSS syntax or that LESS doesn’t recognize. More often than not, it will be some crazy Microsoft hack. To avoid throwing errors and breaking LESS, you will need to escape them.

.class {
	filter: ~"progid:DXImageTransform.Microsoft.Alpha(opacity=20)";
}

/* Will actually be outputted like this: */
.class {
	filter: progid:DXImageTransform.Microsoft.Alpha(opacity=20);
}

JavaScript Evaluation

This is one of my favorite parts of LESS: using Javascript in style sheets — simply brilliant. You can use expressions and also reference aspects of the environment using backticks.

@string: `'howdy'.toUpperCase()`; /* @string becomes 'HOWDY' */

/* You can also use the previously mentioned interpolation: */
@string: 'howdy';
@var: ~`'@{string}'.topUpperCase()`; /* becomes 'HOWDY' */

/* Here we access part of the document */
@height = `document.body.clientHeight`;

Output Formatting

Whereas LESS has no output settings, Sass provides four output versions: nested, compact, compressed and expanded.

Final Thoughts

These two libraries share a lot of basics. Both of them are fantastic tools for designers who code, and they can also help developers work more efficiently and quickly. If you’re a fan of Ruby or HAML, then Sass might be right up your ally. For me, being a PHP and JavaScript geek, I tend to lean towards LESS for its ease of inclusion and access to JavaScript’s expressions and document attributes. I doubt that I’ve even come close to truly grasping the possibilities of programming in my style sheets, but I am intent on trying. If you’ve been using either, or both, of these in your work, I’d love to hear more about it and see some of your results. Tips, tricks and corrections are, of course, always welcome as well.

Sencha the Layout Manager

Sencha Using the hbox and vbox Layout Managers

I am just trying myself to brief about layout management in Sencha; Sencha the Layout Manager

The hbox layout manager orients nested components along the horizontal axis.
The vbox layout manager operates identically to the hbox layout manager, except that it orients components along the vertical axis.

The following example illustates using a simple hbox layout:

Ext.Viewport.add([
{
xtype: 'container',
layout: 'hbox',
cls: 'colorize',
width: 200,
height: 100,
defaults: {
xtype: 'component',
cls: 'colorize',
margin: '5 5 5 5'
},
items: [
{ html: 'Hello' },
{ html: 'World' }
]
}
]);

Using Flex Sizing

You can assign the flex property to any component that is participating in an hbox or vbox layout. The flex property sizes components relative to each other as illustrated by the following example. Note that the “Hello” component is flexed to be twice the size as the “World” component.

Ext.Viewport.add([
{
xtype: 'container',
layout: 'hbox',
cls: 'colorize',
width: 200,
height: 100,
defaults: {
xtype: 'component',
cls: 'colorize',
margin: '5 5 5 5'
},
items: [
{ html: 'Hello', flex: 2 },
{ html: 'World', flex: 1 }
]
}
]);

Centering Components in a Layout

Use the pack configuration property of the hbox or vbox layout to control whether the nested component items should align to the left edge, right edge, center, or be justified in their container.

The following example centers nested components in their parent container:

Ext.Viewport.add([
{
xtype: 'container',
layout: {
type: 'hbox',
pack: 'center'
},
cls: 'colorize',
width: 200
height: 100,
defaults: {
xtype: 'component',
cls: 'colorize',
margin: '5 5 5 5'
},
items: [
{ html: 'Hello' },
{ html: 'World' }
]
}
]);

Valid values for the pack attribute are ‘left’ (default), ‘right’, ‘center’, and ‘justify’:

Layout Config Result
{
type: ‘hbox’,
pack: ‘left’
}
pack: 'left'
{
type: ‘hbox’,
pack: ‘right’
}
pack: 'right'
{
type: ‘hbox’,
pack: ‘center’
}
pack: 'center'
{
type: ‘hbox’,
pack: ‘justify’
}
pack: 'justify'

 

Aligning Components in a Layout

Use the align configuration property of the hbox or vbox layout to designate whether the nested containers should “stretch” across the opposing axis. For example, in an hbox layout, configuring align: ‘stretch’ would expand the child components vertically. In a vbox layout, configuring align: ‘stretch’ would expand the child components horizontally.

Valid values for the align attribute are ‘stretch’,’start’, ‘end’, and ‘center’.

Layout Config Result
{
type: ‘hbox’,
pack: ‘center’,
align: ‘center’
}
using align:center in an hbox
{
type: ‘hbox’,
pack: ‘center’,
align: ‘stretch’
}
align: 'stretch'
{
type: ‘hbox’,
pack: ‘center’,
align: ‘start’
}
align: 'start'
{
type: ‘hbox’,
pack: ‘center’,
align: ‘end’
}
align: 'end'

Bootstrap Migrating from 2.x to 3.0

Bootstrap Migrating from 2.x to 3.0

Bootstrap 3 is not backwards compatible with v2.x. Use this section as a general guide to upgrading from v2.x to v3.0. For a broader overview, see what’s new in the v3.0 release announcement.

Major class changes
This table shows the style changes between v2.x and v3.0.

Bootstrap 2.x Bootstrap 3.0
.container-fluid .container
.row-fluid .row
.span* .col-md-*
.offset* .col-md-offset-*
.brand .navbar-brand
.nav-collapse .navbar-collapse
.nav-toggle .navbar-toggle
.btn-navbar .navbar-btn
.hero-unit .jumbotron
.icon-* .glyphicon .glyphicon-*
.btn .btn .btn-default
.btn-mini .btn-xs
.btn-small .btn-sm
.btn-large .btn-lg
.alert-error .alert-danger
.visible-phone .visible-xs
.visible-tablet .visible-sm
.visible-desktop Split into .visible-md .visible-lg
.hidden-phone .hidden-xs
.hidden-tablet .hidden-sm
.hidden-desktop Split into .hidden-md .hidden-lg
.input-small .input-sm
.input-large .input-lg
.control-group .form-group
.control-group.warning .control-group.error .control-group.success .form-group.has-*
.checkbox.inline .radio.inline .checkbox-inline .radio-inline
.input-prepend .input-append .input-group
.add-on .input-group-addon
.img-polaroid .img-thumbnail
ul.unstyled .list-unstyled
ul.inline .list-inline
.muted .text-muted
.label .label .label-default
.label-important .label-danger
.text-error .text-danger
.table .error .table .danger
.bar .progress-bar
.bar-* .progress-bar-*
.accordion .panel-group
.accordion-group .panel .panel-default
.accordion-heading .panel-heading
.accordion-body .panel-collapse
.accordion-inner .panel-body

What’s new

Bootstrap added new elements and changed some existing ones. Here are the new or updated styles.

Element Description
Panels .panel .panel-default .panel-body .panel-title .panel-heading .panel-footer .panel-collapse
List groups .list-group .list-group-item .list-group-item-text .list-group-item-heading
Glyphicons .glyphicon
Jumbotron .jumbotron
Extra small grid (<768px) .col-xs-*
Small grid (≥768px) .col-sm-*
Medium grid (≥992px) .col-md-*
Large grid (≥1200px) .col-lg-*
Responsive utility classes (≥1200px) .visible-lg .hidden-lg
Offsets .col-sm-offset-* .col-md-offset-* .col-lg-offset-*
Push .col-sm-push-* .col-md-push-* .col-lg-push-*
Pull .col-sm-pull-* .col-md-pull-* .col-lg-pull-*
Input groups .input-group .input-group-addon .input-group-btn
Form controls .form-control .form-group
Button group sizes .btn-group-xs .btn-group-sm .btn-group-lg
Navbar text .navbar-text
Navbar header .navbar-header
Justified tabs / pills .nav-justified
Responsive images .img-responsive
Contextual table rows .success .danger .warning .active
Contextual panels .panel-success .panel-danger .panel-warning .panel-info
Modal .modal-dialog .modal-content
Thumbnail image .img-thumbnail
Well sizes .well-sm .well-lg
Alert links .alert-link

What’s removed

The following elements have been dropped or changed in v3.0.

Element Removed from 2.x 3.0 Equivalent
Form actions .form-actions N/A
Search form .form-search N/A
Form group with info .control-group.info N/A
Fluid container .container-fluid .container (no more fixed grid)
Fluid row .row-fluid .row (no more fixed grid)
Controls wrapper .controls N/A
Controls row .controls-row .row or .form-group
Navbar inner .navbar-inner N/A
Navbar vertical dividers .navbar .divider-vertical N/A
Dropdown submenu .dropdown-submenu N/A
Tab alignments .tabs-left .tabs-right .tabs-below N/A
Nav lists .nav-list .nav-header No direct equivalent, but list groups and .panel-groups are similar.

Additional notes

Other changes in v3.0 are not immediately apparent. Base classes, key styles, and behaviors have been adjusted for flexibility and our mobile first approach. Here’s a partial list:

  • By default, text-based form controls now receive only minimal styling. For focus colors and rounded corners, apply the .form-control class on the element to style.
  • Text-based form controls with the .form-control class applied are now 100% wide by default. Wrap inputs inside <div></div> to control input widths.
  • .badge no longer has contextual (-success,-primary,etc..) classes.
  • .btn must also use .btn-default to get the “default” button.
  • .container and .row are now fluid (percentage-based).
  • Images are no longer responsive by default. Use .img-responsive for fluid <img> size.
  • The icons, now .glyphicon, are now font based. Icons also require a base and icon class (e.g. .glyphicon .glyphicon-asterisk).
  • Typeahead has been dropped, in favor of using Twitter Typeahead.
  • Modal markup has changed significantly. The .modal-header, .modal-body, and .modal-footer sections are now wrapped in .modal-content and .modal-dialog for better mobile styling and behavior.
  • The HTML loaded by the remote modal option is now injected into the .modal instead of into the .modal-body. This allows you to also easily vary the header and footer of the modal, not just the modal body.
  • JavaScript events are namespaced. For example, to handle the modal “show” event, use 'show.bs.modal'. For tabs “shown” use 'shown.bs.tab', etc.

Understanding event handlers in JavaScript

Understanding event handlers in JavaScript

What is event handlers? Its very powerful and useful;

They are JavaScript code that are not added inside the <script> tags, but rather, inside the html tags, that execute JavaScript when something is triggered or called, such as pressing a button, moving your mouse over a link, submitting a form and so on.

The basic syntax of these event handlers is:

name_of_handler=”JavaScript code here”

For example:

<a href="http://www.prasadk.com" onClick="alert('Hi')">prasadk.com Home</a>

Click here to have a look prasadk.com Home

This is certainly unlike a regular JavaScript code, here we are inserting it directly inside a HTML tag, via the onClick event handler. When the above link is clicked, the user will first see an alert message before being taken to home / index page of http://www.prasadk.com.

Different event handlers with with different HTML tags. For example, while “onclick” can be inserted into most HTML tags to respond to that tag’s onclick action, something like “onload” only works inside the <body> and <img> tags.

Listed some of the most commonly used event handlers supported by JavaScript below:

 Event Handlers:

onclick: Use this to invoke JavaScript on clicking (a link, or form boxes)
onload: Use this to invoke JavaScript after the page or an image has finished loading.
onmouseover: Use this to invoke JavaScript if the mouse has been hovered on some link
onmouseout: Use this to invoke JavaScript if the mouse goes pass some link or gets triggered when mouse is taken out of link
onunload: Use this to invoke JavaScript right after someone leaves the page.

In OOP / Object Oriented Event Handlers in Javascript

By default, when an event occurs in javascript, the this reference in the handler function refers to the HTML element.
But what if we want the ‘this’ to refer to the class that houses our handler? We can use the bind()function – see below.

It works like this / snippet


Function.prototype.bind = function (obj) {
    var fn = this;
    return function () {
      var args = [this];

      for (var i = 0, ix = arguments.length; i < ix; i++) {
        args.push(arguments[i]);
      }
      return fn.apply(obj, args);
    }
  }

  function myClass() {
    this.name = "Member variable of myClass()!!";

    myClass.prototype.alertThis = function(el, e) {
      if (!e) var e = window.event;
      alert(this.name);   //we have access to our class object
      alert("id: " + el.id);       //we have access to the element that was clicked
      alert("id: " + e.target.id); //we have access to our event
    }.bind(this);

    var el = document.getElementById("myDiv");
    el.onclick=this.alertThis;
  }

  function onLoad() {
    window.c = new myClass();
  }

  if (window.addEventListener){
    window.addEventListener('load', onLoad, false); 
  } else if (window.attachEvent){
    window.attachEvent('onload', onLoad);
  }

 

Touch Event handlers for touch screen devices :

Some more event handlers are like touchstart, touchmove, touchend, touchcancel, tap, taphold, swipe, swipeleft, swiperight

snippet given below

function touchHandler(event) {
    var touch = event.changedTouches[0];

    var simulatedEvent = document.createEvent("MouseEvent");
        simulatedEvent.initMouseEvent({
        touchstart: "mousedown",
        touchmove: "mousemove",
        touchend: "mouseup"
    }[event.type], true, true, window, 1,
        touch.screenX, touch.screenY,
        touch.clientX, touch.clientY, false,
        false, false, false, 0, null);

    touch.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
}

function init() {
    document.addEventListener("touchstart", touchHandler, true);
    document.addEventListener("touchmove", touchHandler, true);
    document.addEventListener("touchend", touchHandler, true);
    document.addEventListener("touchcancel", touchHandler, true);
}
$(document).ready(function(){
  init();
});

 

PN : while handling the touch event don’t forget to include jQuery, jQuery UI and jQuery mobile from cdn