Tuesday, July 9, 2013

Using self in javascript closures

The setTimeout function in javascript is very interesting in the sense that when it is called, the window object calls it.
Therefore, the original reference to the "this" object is changed; however, to overcome this we can make a copy of the "this" reference related to the closure inside the test function.
Here we call that variable self. This way, when the setTimeout function is called the email is not undefined.



var b = 'test';
//creates an object literal with a function called ;
var x = {
   email: 'test@test.com',
   alertEmail: function() {
   var self = this;
   setTimeout(function(){
   alert(self.email);
   }, 1000);
   }
};

//alerts test@test.com
x.alertEmail();

Saturday, May 11, 2013

Using routes with Angular JS is so easy!


Angular routes make it really easy to build single page applications where you can switch back and forth between pages super fast. And it's so simple...All you need to do is inject your $routProvider into your config and then, based on the routes that you specify in the when function, you can define which templates will show up in the view...specified by the ng-view directive in your application... Furthermore, you can define what controller will be used when that template is loaded for that route...

See below...Here is a simple example of setting up some different pages...

myApp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$locationProvider.hashPrefix('!');

$routeProvider.
    when('/', {templateUrl: 'partials/home.html',   controller: HomeCtrl}).
    when('/about', {templateUrl: 'partials/about.html',   controller: HomeCtrl}).
    when('/contact', {templateUrl: 'partials/contact.html',   controller:     HomeCtrl}).
    otherwise({redirectTo: '/'});
}]);