UXnUI

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

Remove input field and textarea inner shadow in iOS

Remove input field and textarea inner shadow in iOS

How to Remove input field text and text-area inner shadow in iOS:

Apple/iOS products are great, but the mobile iOS is adding extra styles to form elements.

This can be quite annoying if you want to get your design to look exactly the same in most browsers/hybrid apps.

Here is how you can remove inner shadow from text input fields and textareas by simply applying the CSS to your input text field and textarea.


/* Remove inner shadow from input type="text" and textarea on mobile iOS */

textarea, input[type="text"] {
-webkit-appearance: none;
}

What is CSS Box Shadow?

CSS Box Shadow. Used in casting shadows off block-level elements (like divs). … The vertical offset of the shadow, a negative one means the box-shadow will be above the box, a positive one means the shadow will be below the box.


inner shadow in iOS

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.