Getting Started with Backbone.js Routes – Part II: Handling Bad Requests

Backbone

Backbone.js LogoLearn how to handle requests for a route that you have not configured

In the first part of this series: Getting Started with Backbone.js Routes – Part I: Introduction, we learned how to set up routing in a single page web application. We covered two kinds of routes: a “default” route (i.e. no route is requested), and a named route.

In this article, we will learn how to configure a Backbone router for a bad request. To be specific, a bad request would be one that you have not anticipated (i.e. you have not configured your router for that specific request). In the previous example, if you were to request a route other than “info”, there would be no error, but this is an unhandled case, and not the best user experience.

Here are two examples of unhanded exceptions from Part-I of this series:

http://examples.kevinchisholm.com/backbone/routes/basics/html/part-i.html#/bad-request

http://examples.kevinchisholm.com/backbone/routes/basics/html/part-i.html#/another-bad-request

In both cases, the page loads, but there is no message because the router was not configured to handle the routes: “#/bad-request” and “#/another-bad-request”.

Example # 1

In Example # 1, we have updated the object passed to the Backbone.Router.extend method. There is now a third route named: “*actions”. This tells Backbone that if a request is not one of the first two specified (i.e. “” and “info”), then execute the “pageNotFound” method.

The “pageNotFound” method is similar to the other route handlers, but injects a message into the DOM that is specific to this scenario: the user has requested a route that does not exist. This way, instead of “nothing” happening, you can present very specific content to the user.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1: http://examples.kevinchisholm.com/backbone/routes/basics/html/part-ii.html

How to Demo:

When the page loads, you will see the message: “This is the default route”, and if you click the “info” link, you will see the message: This is the “Info” page. But if you click the link: “Bad request”, you will see the message: “Sorry, the page you requested was not found”. The reason for this is that there is no route configured for: “#/bad-request”. In fact, no matter what you request, unless that route request is: “” or “info”, then you will see the message: “Sorry, the page you requested was not found”

Here are a few examples:

http://examples.kevinchisholm.com/backbone/routes/basics/html/part-ii.html#/no-route-here

http://examples.kevinchisholm.com/backbone/routes/basics/html/part-ii.html#/no-route

http://examples.kevinchisholm.com/backbone/routes/basics/html/part-ii.html#/not-handled

When you click any of the links above, you will still get the message: “Sorry, the page you requested was not found”.

Summary

In this article, we learned how to configure our Backbone router to handle bad requests. We discussed the “*actions” property of the “routes” object, and how to make sure it is the last property specified in that object. We also set up a function to be executed whenever a bad route request is made.

Getting Started with Backbone.js Routes – Part I: Introduction

Backbone

Backbone.js LogoLearn the simple yet powerful syntax for setting up routing in your Backbone.js single page application

Routes are one of the most important aspects of any single page application. Routes allow you to intercept browser address changes and act upon them accordingly. As per the moniker “single page application” suggests, after the completion of the initial page load, you never want the user to endure a round-trip to the server.

Backbone.js provides simple yet powerful abstraction for routing. In this series of articles, we will explore the core syntax and features that allow you to build-out routing for your single page application.

Extending Backbone.Router

Extending classes is an important topic to quickly review. In Backbone.js, when you want to create a router, you first need to extend the Router class. To be more specific, “Router()” is a JavaScript constructor function that is a property of the “Backbone” object. Extending the Router class allows you to leverage all of the existing functionality while adding more of your own. When you extend the Router class, you are creating a new constructor that inherits from the “Backbone.Router”. Once you have extended the Router class, you’ll then need to instantiate your new constructor.

Example # 1A

Example # 1B

In example # 1A, we create a new variable named: “AppRouter”, and set it to the return value of Backbone.Router’s “extend” method. The “extend” method allows you to create a class that inherits from another and is available in a number of Backbone objects. In this case, our class does not do too much, so we have a bit more work to do.

In example # 1B, notice that an object is being passed to the extend method. This object is empty, and our AppRouter class still does not offer much value. The main points to remember as we move forward are:

You create a router by extending the Backbone.Router class, using the “extend” method
The extend method requires an object as its sole argument
The result of extending the Backbone.Router class is a new class (or constructor), which will need to be instantiated

NOTE: Our variable begins with a capital “A” (i.e. “AppRouter”). This is not required but it is recommended because in JavaScript (as well as other languages), classes usually have an initial capital letter in their name.

Example # 2

In Example # 2, we have added quite a bit of functionality to the object that is passed into the extend method. This object has three properties: “routes”, “home”, and “info”.

The “routes” property is critical. This property is an object. The properties of the object are the routes that we want to map. In this case, there are two:

  • “” – When no route is requested, map to “defaultRoute”
  • “into” – When an “info” route is requested, map to “info”

But, what are “home” and “info”? Well, they are the other two two properties of the object passed to the extend method, and they are method (i.e. they are properties whose value is a function). So, when no route is requested, Backbone will execute the “defaultRoute” method, and when the “info” route is requested, the “info” method will be executed.

This example is very basic; you are not likely to create a single page application with only two routes. What is important to remember is that as you build out your application, this is a pattern you will follow:

  • You extend the Backbone.Router class by passing an object to the extend method
  • In the object you pass to the extend method, you provide a “routes” property
  • The “routes” property is an object that has a set of properties that map to methods
  • The methods you map to are functions that handle the route request

There are still a couple of steps left in order to get our new Router to a working state.

Example # 3

In Example # 3, we take two further steps that are needed in order to get our Backbone.js router to a working state:

  1. We instantiate our AppRouter class
  2. We call Backbone.history.start(); from the jQuery document.ready method.

The first step is required because even though we extended the Backbone.Route class, we need to instantiate the new class (or constructor) that we created. A detailed discussion of the Backbone.history object and its “start” method is beyond the scope of this article, but suffice to say that this step is needed in order to get the routing process started. Wrapping it in a call to jQuery’s document.ready method is generally a good idea so that you can be sure that the routing does not start until the DOM is ready.

HERE IS THE LINK TO THIS ARTICLE’S WORKING EXAMPLE:

http://examples.kevinchisholm.com/backbone/routes/basics/html/part-i.html

How to Demo:

Click the “Home” and “Info” links in the page’s navigation menu. As you do this, look closely at the browser’s address bar. You’ll see that “#/” and “#/info” are appended to the address. These are routes. The code that we worked on in this article intercepts these route requests and prevents the page from making a request to the server located at: “http://examples.kevinchisholm.com/”. Accordingly, messages that are results of the functions we execute upon each route request are rendered in the DOM.

Details

When the page loads, you will see the following message: “This is the default route”.The reason for this is that when we extended Backbone.Route, we specified that if no route was requested, the “defaultRoute” method should execute. If you click the “Info” menu item, you’ll see the message: This is the “Info” page. This is because we specified that when the “info” route is requested, the “info” method should execute.

Summary

In this article, we were introduced to Backbone’s routing feature. We learned about extending classes, and specifically, the syntax needed to create a constructor function that inherits from Backbone.Router. We discussed the steps needed to configure our router so that a number of possible routes can be anticipated and acted upon accordingly.

Helpful Links for Routing in Backbone.js

http://backbonejs.org/#Router

http://backbonetutorials.com/what-is-a-router/

http://www.codebeerstartups.com/2013/01/routers-in-backbone-js-learning-backbone-js

Getting Started with Angular 1.x Custom Directives – Part III – The “restrict” property

Angular

Angular.js LogoLearn how the “restrict” property determines how your Angular.js directive can be invoked

In the second part of this series: Getting Started with Angular.js Custom Directives – Part II – The “replace” property, we learned about how to use the “replace” property when creating a custom Angular.js directive. This determines whether the element that your directive renders will be a child of the element that invoked it, or a complete replacement of that element.

In this article, we will learn about the “restrict” property that, which allows you to specify the ways in which your custom directive can be invoked.

Example # 1:

 

In Example # 1, we have created a custom Angular.js directive named: “uiWidget”. In addition to the “template” and “replace” properties that were discussed in previous articles, we have created a “restrict” property. This property allows you to specify the way in which the directive is invoked. Notice that the value is: “AECM”. These letters stand for:

  • A : Attribute
  • E : Element
  • C : Class
  • M : Comment

You can use any one of the values by itself, or any combination.

Example # 2:

In Example # 2, we have four snippets of HTML. In each case, we demonstrate a different way to invoke our custom Angular.js directive.

First, as an attribute of the HTML element. Notice how the attribute has no value. In our case, the mere presence of the attribute signals to Angular that our custom directive should be invoked.

Second, as an element. Although there is no such thing as a “ui-widget” HTML tag, Angular will recognize this element and invoke our custom directive.

Third, as a CSS class of the element.

Fourth, as a comment. This approach may seem a bit odd, but you can, in fact, trigger your custom Angular.js directive via an HTML comment.

HERE IS THE LINK TO THE WORKING EXAMPLE FOR THIS ARTICLE: http://examples.kevinchisholm.com/angular/directives/basics/html/part-iii.html

Summary

In this article, we learned about the “restrict” property of the object returned by an Angular directive. We discussed the four possible values for this property, and how each case differs.

Getting Started with Angular. 1.x Custom Directives – Part II – The “replace” property

Angular

Angular.js LogoLearn how your Angular.js directive’s “replace” property determines how it is rendered in the DOM

In the first part of this series: “Getting Started with Angular.js Custom Directives – Part I“, we learned the absolute basics of how to create a custom Angular.js directive. In that article, we learned how to create an Angular module, and then call that module’s “directive” method, which takes a function as its second argument. In that function we returned an object with a “template” property, which contained HTML that would become the actual directive, once injected into the DOM.

In this article, we will learn about the “replace” property, which is a member of the object returned by the directive method. This property is a Boolean, so it has two possible values: true and false. When false, your directive’s HTML is injected into the DOM as a sibling of whatever content is already there. When true, your directive completely replaces the element.

Example # 1A:

In Example # 1A, we have HTML that invokes two Angular directives: “ui-widget-replace” and “ui-widget-no-replace”. Both DIVs look are empty and other than the slight variation in the directive name, they look identical.

Example # 1B:

In Example # 1B, we have the JavaScript that defines these two directives. The “uiWidgetNoReplace” directive has its “replace” property set to: “false”. As a result, the widget that is rendered in the DOM is a child element of the element that invoked the widget (i.e. the element with the “ui-widget-no-replace” attribute). The “uiWidgetReplace” directive has its “replace” property set to: “true”. As a result, the widget that is rendered in the DOM REPLACES the element that invoked the widget. In other words: the element with the “ui-widget-no-replace” attribute is replaced by the widget.

Example # 1C:

In Example # 1C, we see the result of our HTML and JavaScript. The first element completely wraps the widget markup, whereas the second element is the widget (i.e. the widget has completely replaced the markup that declared the ui-widget directive).

This result can be verified when you look at the link for the working example. The element with the attribute: “ui-widget-no-replace” has a blue border, and the element with the attribute: “ui-widget-replace” has a red border. Also, you’ll notice that the first widget is has an inner box with a yellow border. This is because there is a parent-child relationship going on here; because the “replace” property’s value is false, the widget is injected into the DOM as a child of the element that invoked the directive. You can view the page source and examine the CSS to see how this style has been applied.

IMPORTANT: Note that we actually create three modules: “myModNoReplace“, “myModReplace“, and “myMod“. The “myMod” module is the main component used in the page, and it declares the modules: “myModNoReplace” and “myModReplace” as dependencies. Module dependencies is a topic that is beyond the scope of this article, and will be covered in a future post. Just know that in order to have multiple modules used in a page, you’ll need to follow this kind of pattern.

HERE IS THE LINK FOR THIS ARTICLE’S WORKING EXAMPLE:

 http://examples.kevinchisholm.com/angular/directives/basics/html/part-ii.html

Summary

In this article, we learned about the “replace” property. This boolean value allows you to determine whether or not the HTML that makes up your custom directive will completely replace the element that declares our directive, or make it a child element.

Getting Started with Angular 1.x Custom Directives – Part I – Introduction

Angular

Angular.js Logo
Learn how to create your own Angular.js directive (it’s much easier than you think!)

It’s hard to imagine any kind of interaction with Angular that does not involve directives. Angular directives allow you to super-charge your HTML, or even create your own tags.

While there is certainly a generous helping of built-in Angular directives, you don’t have to be satisfied with what comes in the box. You can create your own Angular directives. Not only that, but the way your directive is invoked, what it does, and how it works is completely up to you. Because of the kind of abstraction Angular provides, you are limited only by your imagination.

In this article, we will learn how to create our own Angular directive. This is a fairly deep topic, with plenty of detailed discussions to jump into, many of which will be covered in upcoming editions of this series. For this article, we will focus on the core syntax needed to create a directive and have it render something in the DOM.

Example # 1A

In Example # 1A, we create an angular module named: “widgetApp”, and assign it to the variable “myMod”. The syntax is pretty simple: You call the module method of the angular object, passing it two arguments. The first argument is a string, which is the name by which this module will be known by other modules. What is this means is that if this module is to be considered a dependency by one or more other modules, this string is the name by which those modules will call your new module. The second argument is an array. This array can contain one or more dependencies. If your directive will have no dependencies, you can leave this array empty, but it must be there (i.e., you can’t omit the array).

Example # 1B

In Example # 1B, we have created a custom directive by calling the angular.module’s “directive” method. The first argument is a string: the directive’s external name; that is, this is the name by which you will refer to your directive in the DOM.

The second argument is a function. This function is where we will do the work required to create the directive. Notice that the function returns an object. While this object is empty in our example, it is required. So, even though we return an empty object, we are ok (but you must return an object).

While this directive effectively does nothing, the syntax is correct and there will be no errors on page load. But since our directive has no actual functionality, we will need to put a bit more effort into this.

Example # 2

In Example # 2, we have made a small addition to the anonymous function that is passed to the angular.module’s “directive” method: the object that we return now has one property: “template”. This “template” property’s value is a string of HTML that will be injected into the DOM.

This could be considered the bare minimum needed for a directive that actually renders in the DOM: You return an object that has a “template” property. There is still not too much going on here. Our custom “uiWidget” directive simply adds a DIV element to whichever element calls the directive, and the text of that DIV is: “This is a Widget”.

HERE IS THE WORKING CODE EXAMPLE LINK FOR EXAMPLE # 2: http://examples.kevinchisholm.com/angular/directives/basics/html/part-i.html

Hey Kevin, isn’t creating a custom Angular directive supposed to be a bit more exciting than this?

While injecting “This is a Widget” into the DOM is not a particularly eventful outcome here, the areas we covered are important. Any custom directive you create in the future will follow this exact same pattern. The are many more properties that can be members of the return object, and there is a tremendous amount of power and flexibility available when creating a directive. But remember: as you learn more about custom directives in Angular, every concept covered in this article will still apply.

Summary

In this article we learned the absolute basics about how to create a custom Angular.js directive. Although we barely scratched the surface, we did cover the critical details needed in order to create a directive that actually renders somethign in the DOM. We learned how to create an Anuglar module, and then use that module’s “directive” method to create the directive. We also discussed how the directive is created in a function, and how that function must return an object. That object’s “template” property will contain the HTML that will be rendered in the page.

Easy Text Input “Hints” with the HTML <datalist> Tag

HTML5

HTML5 Logo
Provide helpful “hint” functionality for your text-inputs with just a little bit of hidden markup: the <datalist> element!

One of the newer HTML5 elements that I hear very little about is the Datalist tag. I’m a bit surprised by this because the datalist element is super-easy to implement and quite helpful.

In a nutshell, this tag provides easy “hint-like” behavior for text-inputs.

Surely we’ve all seen how some websites will provide “hints” as you type in a text-box. One of the most common examples, of course, is Google search. As you type, a list of words that match your input appear in and below the text box.

Most noteworthy: the HTML5 Datalist tag is not supported in Internet Explorer version 9 and below, nor Safari. But I think most would agree that this feature is an enhancement. So, you could implement it in your page, and consider it a “nice to have” if the user’s browser supports it.

Needless to say, any real-time “wildcard” implementation of this concept requires not only AJAX but some pretty serious back-end engineering that will provide useful hints quickly.

But what if you have a fairly strong idea of what the user “might” type. For example, let’s say that you prompt the user to enter the name of a European country in a text box. While that text box may allow any input, the user is likely to enter words such as “Austria”, “Belgium” or “Czech Republic”. So, why not add a little sugar to your page and “suggest” some of those words as they type?

Example # 1

Here in Example # 1, we have a very simple HTML form. Below that is the HTML5 Datalist element. That list is bound to the form by setting the form’s “list” attribute to the ID of the datalist (i.e. “euroCountries”).

Yes, it really is that simple.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1: http://jsfiddle.net/z99Jx/3/

How to Demo: When you view the JsFiddle.net link for Example # 1, you will see a text-input field in the output area. So, you just put your cursor in that input field and type any letter between “A” and “F”. And, of course, as you type, any country from the “euroCountries” list that has that letter in its name appears as a “hint”.

Oh my goodness… it really is that simple!

Example # 2

Now, here in Example # 2, there is code that you can run against this very web page. You may notice that in the upper-right-hand corner of this page, there is the text: “Search This Blog”. Below that is a text-input. If you type any letter between “A” and “F” right now, nothing happens.

Copy the code from Example # 2, paste it into your JavaScript console, and then execute it. Now, when you type any letter between “A” and “F”, any country from the “euroCountries” list that has that letter in its name appears as a “hint”.

Summary

In this article we learned about the new HTML5 Datalist tag. We also learned how this element can be used to provide “hints” for text input form elements. And finally, we learned how to bind that list to an input element, and set a list of options that will become the “hints”.

Helpful Links for the HTML5 Datalist tag

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist

http://caniuse.com/datalist

http://www.htmlgoodies.com/html5/markup/whats-new-in-html5-forms-the-datalist-control.html#fbid=NYUB4nW2C7h

http://www.quackit.com/html_5/tags/html_datalist_tag.cfm

http://webdesign.tutsplus.com/tutorials/introducing-the-html5-datalist-element–webdesign-9888

http://davidwalsh.name/datalist

JavaScript Interview Questions – Functions

JavaScript

JavaScript LogoBefore you head into that interview, make sure you understand how functions work, and the various components of their behavior.

Functions play a major role in the JavaScript language. In addition to providing private scope, they allow you to organize blocks of code for later execution. While most front-end developers have used JavaScript functions many time, there are some core areas of knowledge that are important to know.

I consider the following topics to be the baseline for a decent understanding of JavaScript functions.


Q: What is the length of the above function named: “foo”?
A: 3

Hint: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length


Q: In a function, what does the word “arguments” refer to?
A:
It is a property of the function, and is an array-like list of the arguments that were actually passed into the function
Hint: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments


Q: What does the above function return?
A: “undefined” (without quotes)
Hint: If you do not specify a return value in a function, it returns undefined .

return – JavaScript | MDN

undefined – JavaScript | MDN


Q: Given the above code, what will be the console output when foo() is executed?
A: “hello there undefined”
Hint: When a function executes, any  arguments that are not passed-in have a value of: undefined.


Q: Given the code above, how would you programatically obtain a string representing the source code of the function?
A: foo.toString()
Hint:
Function.prototype.toString() – JavaScript | MDN


Q: Given the above code, how would you change the call to: “executeFunction” function, so that it will execute the “sayHello” function?
A:

Hint:

javascript pass function as parameter – Stack Overflow


Q: Given the above code, how would you change the call to the: “alertGreeting” function, so that it will alert the return-value of the “getGreetingText” function ?
A:

Hint:

Functional Programming — Eloquent JavaScript


Q: Given the code above, how would you change the “isFunction” function so that when it is passed a function, it returns true, and if not, it returns false?
A:

Hint:
Use the JavaScript “instanceof” operator:  instanceof – JavaScript | MDN


Q: Given the code above, how would you change the “sayHello” function so that it executes immediately after it id defined? (i.e. there is no need to call it, it executes right-away)

A:

Hint: You can turn that function into a self-executing or “immediate” function by wrapping it in parentheses, and adding a pair of parentheses after that: (yourFunctionHere)().

Immediate Functions in JavaScript – The Basics | Kevin Chisholm – Blog

Immediately-invoked function expression – Wikipedia, the free encyclopedia

JavaScript Interview Questions – Beginner

JavaScript

These are basic JavaScript questions that any front-end web developer should be able to answer.


Q: What is the keyword used when declaring variables that makes them private to a function?

A: “var”
Hint: http://stackoverflow.com/questions/1470488/difference-between-using-var-and-not-using-var-in-javascript


Q: What is the one and only way to control variable scope in JavaScript?
A: Functions
Hint: http://blog.kevinchisholm.com/javascript/scope/


Q: What are the two possible values of a boolean type?
A: true and false
Hint: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Boolean


Q: Which web browser implements Document.attachEvent()?
A: Internet Explorer 8 and below
Hint: http://msdn.microsoft.com/en-us/library/ie/ms536343(v=vs.85).aspx


Q: How do you create a DIV element using JavaScript?
A: document.createElement(‘div’)
Hint: https://developer.mozilla.org/en-US/docs/DOM/document.createElement


Q: if var foo = “hello”, how do I coerce foo to be a false value?
A: !foo
Hint: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Logical_Operators


Q: If I have var foo = document.createElement(‘img’), how do I set the “src” attribute of that image element to “someimage.jpg”?
A: foo.src = “someimage.jpg”
Hint: http://www.javascriptkit.com/jsref/image.shtml


Q: How would you check if the variable “foo” is equal to exactly 5 OR is equal to exactly 7?
A: if (foo === 5 || foo === 7){ // do something here…};
Hint: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Logical_Operators


Q: What is the difference between “=”, “==” and “===” in JavaScript?
A: “=” assigns a value, “==” checks for equal value, “===” checks for equal value and type
Hint: http://stackoverflow.com/questions/4846582/what-is-difference-between-and-in-javascript


Q: Does Internet Explorer Implement Event Capturing?
A: Only IE 9 and above
Hint: http://javascript.info/tutorial/bubbling-and-capturing

The JavaScript “this” Keyword Deep Dive: jQuery Click Handlers

JavaScript

JavaScript LogoLearn the difference between $(this) and “this” inside of your jQuery event handler.

In two previous posts, we learned that functions that are properties of an object are called “methods” (The JavaScript “this” Keyword Deep Dive: Nested Methods & The JavaScript “this” Keyword Deep Dive: An Overview). In this case, the JavaScript “this” keyword refers to the object that the method belongs to. Well, of course, this is usually pretty obvious from looking at the code.

But in an event handler, it may not be apparent to all that the JavaScript “this” keyword, is available to you inside of the event handler, and that it refers to the element that generated the event. Since many front-end developers are comfortable with jQuery, I thought I’d start with jQuery event handlers. And since click events are so common, let’s stick with that.

Example # 1

In Example # 1, we have created a click event handler using jQuery. When the user clicks the anchor tag inside of the element with the class: “download”, the jQuery “toggleClas” method is used to change the text “Click Me” fom red to blue.

Of course, many have seen $(this) used inside of the event handler to set a reference to the element that was clicked. It is helpful to know, however, that $(this) is an enhanced version of the JavaScript “this” keyword. That is to say: inside of the click event handler, “this” refers to the element that was clicked. When you put “this” inside of: $( ), you “wrap” the JavaScript “this” keyword with jQuery, which adds a number of properties and methods.

As a result of this “wrapping”, you can set a reference to the element that was clicked, but you can also leverage the power of jQuery. The native JavaScript HTML element does not have a “toggleClass” method, but jQuery does. So, by wrapping the JavaScript “this” keyword with jQuery, $(this) has allowed you to reference the clicked element, and use jQuery methods.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1: http://jsfiddle.net/9gZbE/

How to Demo: Click the text that says: “Click Me”. Each time you click that element, the text color will toggle between red and blue.

Example # 2

In Example # 2, we have changed the reference to the clicked element from $(this) to “this”. But when you click that element, there is an error in the JavaScript console. In Google Chrome, the error is: Uncaught TypeError: Object [object HTMLAnchorElement] has no method ‘toggleClass’, and in FireFox, the error is: TypeError: this.toggleClass is not a function. The reason for this error is that while the JavaScript “this” keyword can be used to reference the element that was clicked, it does not have a “toggleClass” method. So, an error occurs.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/9gZbE/1/

How to Demo: Open up your JavaScript console, and then click the text that says: “Click Me”. When you do, you will see an error indicating that the element you clicked does not have a “toggleClass” method.

Example # 3

So, in Example # 3, we continue to reference the element that was clicked by using the JavaScript “this” keyword, without the jQuery “wrapping”. That is: we are not using: $(this). The reason that the example now works, is because we are using the “classList” property of the element, and in-turn, the “contains”, “remove” and “add” methods. Consequently, this allows us to mimic jQuery’s “toggleClass” method.

It’s important to note that although we used jQuery to create the click handler, we can still use the JavaScript “this: keyword inside of that event handler, and access the native JavaScript element object.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/9gZbE/2/

How to Demo: Click the text that says: “Click Me”. Each time you click that element, the text color will toggle between red and blue.

Summary

In this article, we learned about the JavaScript “this” keyword when used inside of a jQuery event handler. We learned that we can “wrap” that keyword with jQuery, leveraging that library’s DOM manipulation methods. We also discussed how inside of a jQuery event handler, we can still use the “un-wrapped” version of “this”, and leverage native JavaScript DOM manipulation methods.

The JavaScript “this” Keyword Deep Dive: Constructor Functions

JavaScript

JavaScript LogoLearn how the JavaScript “this” keyword differs when instantiating a constructor (as opposed to executing the function).

In earlier articles of the “The JavaScript “this” Keyword Deep Dive” series, we discussed how the meaning of “this” differs in various scenarios. In this article, we will focus on JavaScript constructors. It is critical to keep in mind that in JavaScript, constructor functions act like classes. They allow you to define an object that could exist. The constructor itself is not yet an object. When we instantiate that constructor, the return value of the instantiation will be an object, and in that object, “this” refers to the instance object itself.

So, inside of a constructor function, the JavaScript keyword refers to the object that will be created when that constructor is instantiated.

Example # 1

In Example #1, you’ll see that we have created two new properties of the window object: “music” and “getMusic”. The “window.getMusic” method returns the value of window.music, but it does so by referencing: “this.music”. Since the “window.getMusic” method is executed in the global context, the JavaScript “this” keyword refers to the window object, which is why window.getMusic returns “classical”.

When you instantiate a JavaScript constructor function, the JavaScript “this” keyword refers to the instance of the constructor.

We’ve also created a constructor function named “Foo”. When we instantiate Foo, we assign that instantiation to the variable: “bar”. In other words, the variable “bar” becomes an instance of “Foo”. This is a very important point.

When you instantiate a JavaScript constructor function, the JavaScript “this” keyword refers to the instance of the constructor. If you remember from previous articles, constructor functions act like classes, allowing you to define a “blueprint” object, and then create “instances” of that “class”. The “instances” are JavaScript objects, but they differ from object literals in a few ways.

For an in-depth discussion of the difference between an object literal and an instance object, see the article: “What is the difference between an Object Literal and an Instance Object in JavaScript? | Kevin Chisholm – Blog”.

Earlier on, we established that inside a function that is not a method, the JavaScript “this” keyword refers to the window object. If you truly want to understand constructor functions, it is important to remember how the JavaScript “this” keyword differs inside that constructor. When you look at the code, it seems as if “this” will refer to the window object. If we were to simply execute Foo as if it were a normal function, this would be true (and we will discuss this scenario in Example # 3). But we don’t simply execute Foo; we instantiate it: var bar = new Foo().

When you instantiate a JavaScript constructor function, an object is returned. The JavaScript “this” keyword has a special meaning inside of that object: it refers to itself. In other words, when you create your constructor function, you can use the “this” keyword to reference the object that WILL be created when the constructor is instantiated.

So, in Example # 1, the getMusic method returns “this.music”. Since the “music” property of Foo is: “jazz”, then the getMethod returns “jazz”. When we instantiate Foo, the variable “bar” becomes an instance of Foo, so bar.getMusic() returns “jazz”.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1: http://jsfiddle.net/2RFa3/

Example # 2

In Example # 2, we have changed Foo’s “GetMusic” method. Instead of returning “this.music”, it returns an executed function. While at first glance, it may seem as though the “getMusic” method will return “jazz”, the JSFiddle.net link demonstrates that this is not the case.

Inside of the “getMusic” method, we have defined a variable that is equal to an anonymous function: “myFunction”. Here is where things get a bit tricky: “myFunction” is not a method. So, inside that function, the JavaScript “this” keyword refers to the window object. As a result, that function returns “classical” because inside of “myFunction”, this.music is the same thing as window.music, and window.music is “classical”.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/2RFa3/1/

Example # 3

In Example # 3, we have an example of a scenario that you don’t want: executing a JavaScript constructor function instead of instantiating it. Hopefully, this is a mistake that you will catch quickly, but it can happen. It is also possible that you might inherit code that contains such a bug. Either way, this is bad.

While the Foo constructor still has a “getMusic” method, because we execute Foo, instead of instantiating it, the code inside of Foo overwrites two properties that we created earlier: window.music and window.getMusic. As a result, when we output the value of “this.getMusic()”, we get “jazz”, because when we executed Foo, we overwrote window.music, changing it from “classical” to “jazz”.

While this is a pattern that you want to be sure to avoid in your code, it is important that you be able to spot it. This kind of bug can leave you pulling your hair out for hours.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/2RFa3/2/

Summary

In this article we learned how the JavaScript “this” keyword behaves in a constructor function. We learned about instantiating a constructor and the relationship between “this” and the instance object. We also discussed a couple of scenarios that are important to understand with regards to “this” and constructor functions.

The JavaScript “this” Keyword Deep Dive: Nested Methods

JavaScript

JavaScript LogoDepending on the scenario, the JavaScript “this” keyword may refer to the object of which the method is a property, or the window object.

In an earlier article: The JavaScript “this” Keyword Deep Dive: Nested Functions, we learned how functions that are not methods evaluate “this” to the window object. In that post, we demonstrated that no matter how deeply you nest functions, this behavior is always the same. In this article, we will learn how the JavaScript “this” keyword behaves in nested methods.

So, here, it might be a good idea to quickly answer the question: “What is a nested-method”?

A method is a function that is a property of an object. A nested method occurs when a method, in turn, returns an executed method.

The reason that this scenario is an important one to consider is that while you may execute method A, if that method returns the executed method of object B, then inside of that second method, the JavaScript “this” keyword refers to object B (not object A).

Example # 1

In Example # 1, we have added a property to the window object named “music”, and set the value to: “classical”. We have also added a method to the window object named “getMusic”, which returns the value of window.music. But, notice that instead of referencing window.music, the method returns: this.music. The reason that works is that since the method is a property of the window object, “this” refers to the window object. This means that this.music is the same thing as this.music, and the value of that property is: “classical”.

We have also created an object named “foo”, and it has the exact same-named properties we specified above, and the “getMusic” method has the exact same code: return this.music. But foo’s “getMusic” method returns “jazz”, because foo.music = “jazz”, which means that inside of foo’s “getMusic” method, the JavaScript “this” keyword refers to the foo object, and foo.music is “jazz”.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1: http://jsfiddle.net/5uUJ8/

Example # 2

In Example # 2, we have created an object named: “foo”, which has a method named: “getMusic”. The getMusic method returns an object with two properties: “music”, which is equal to “rock”, and “getMusic” which returns this object’s “music” property.

When we pass the output of foo.getMusic() to the console, we see that is: “rock”, and now “Jazz”. The reason for this is that foo’s getMusic method ignores foo’s music property. That is, it returns an object, and that object’s getMusic method returns its own “music” property. In this scenario, we have nested a method: foo.getMusic, that returns the executed method of another object. The reason for this example is to demonstrate the fact that even though foo.getMusic returns a nested method, when the nested method utilizes the JavaScript “this” keyword, it refers to the object that it is a property of, not foo.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/5uUJ8/1/

Example # 3

So, in Example # 3, we take the exact same approach as Example # 2, providing an additional level of method-nesting. As you might expect, the innermost method returns “metal”, the value of the “music” property to which the getMusic method belongs.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/5uUJ8/2/

Example # 4

Example # 4 is somewhat similar to Example # 3, except that the nesting is logical, not physical: each getMusic method, in turn, calls the getMusic method of a different object. The end result is the same as Example # 3: “metal”. But instead of one method returning an anonymous object whose getMusic method is executed, each of the getMusic method calls here return the execution of another named-object’s “getMusic” method.

It is also important to note that the first console.log call: this.getMusic returns “classical”, because the window.getMusic method is a property of the window object. But, each of the other objects (i.e. “rockObject” and “metalObject”) have its own “music” properties, so when the “metalObject.getMusic” is called, it returns the value of metalObject’s “music” property, which is “metal”.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 4: http://jsfiddle.net/5uUJ8/3/

Summary

In this article we discussed how the JavaScript “this” keyword behaves inside of nested methods. We learned what a nested method is. And we also learned how, in this scenario, the JavaScript “this” keyword refers to the object of which the method is a property, not the window object.

The JavaScript “this” Keyword Deep Dive: Nested Functions

JavaScript

JavaScript LogoLearn how the JavaScript “this” keyword behaves inside of function declarations and expressions, even when nested 10 levels deep.

In the article: The JavaScript “this” Keyword Deep Dive: An Overview, we discussed a number of scenarios in which the JavaScript “this” Keyword has different meanings. In this article, we will concentrate on functions and methods.

It’s important to note that methods are functions. What makes a method a method is that the consumer of the code specifies an object, and then calls a method of that object.

Example # 1

In Example # 1, we have executed a function and a method. We have actually executed two functions, but the second function: “someMethod” is actually a method of the “bar” object. We know this because we have used the syntax: object.method().

It’s important to understand the difference between executing a function and a method.

Example # 2

foo = function (){ return this.music; }; console.log(this.music); //’classical’ (global) console.log(foo()); //’classical’ (global)

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/84Yd4/

In Example # 2, we have executed the function “foo”, which returns the value of “this.music”: “classical”. Both console.log statements return the value: “classical”, because since we are not inside of a method, the JavaScript “this” keyword refers to the window object, and at the top of the code, you’ll see that window.music is equal to “classical”.

Example # 3

foo = function (){ function bar(){ function baz(){ function bif(){ return this.music; } return bif(); } return baz(); } return bar(); }; console.log(this.music); //’classical’ (global) console.log(foo()); //’classical’ (global)

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/84Yd4/1/

In Example # 3, things get a bit silly, but the effect is the same. Even inside of nested functions, because none of these functions are methods, the JavaScript “this” keyword refers to the window object. And “this.music” is the same as “window.music”, which is equal to “classical”.

Example # 4

foo = function (){ function bar(){ function baz(){ function bif(){ function billy(){ function bobby(){ function betty(){ function jetty(){ function jimmy(){ function judy(){ return this.music; } return judy(); } return jimmy(); } return jetty(); } return betty(); } return bobby(); } return billy(); } return bif(); } return baz(); } return bar(); }; console.log(this.music); //’classical’ (global) console.log(foo()); //’classical’ (global)

In Example # 4, the function-nesting concept is taken to a ridiculous level. Nonetheless, the output is exactly the same: “this.music” is the same as “window.music”, which is equal to “classical”. It does not matter how deeply a function is nested. Unless it is a method of an object, the JavaScript “this” keyword will always refer to the window object.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/84Yd4/2/

Summary

In this article we learned that when a function is not specified as a method of an object, the JavaScript “this” keyword refers to the window object. This is true even in the case of nested functions. In fact, no matter how many levels deep we nest functions, the JavaScript “this” keyword refers to the window object.

The JavaScript “this” Keyword Deep Dive: An Overview

JavaScript

JavaScript LogoLearn the subtle yet critical details that allow you to leverage the JavaScript “this” keyword.

In JavaScript, the “this” keyword is one of the most overly-used yet under-utilized aspects of the language. It is also one of the most mis-understood topics. While it facilitates more readable, expressive object-oriented JavaScript, improper use is a catalyst for confusing code that is difficult to debug.

Personally, I’ve struggled to understand the mystery. I’ve heard many unusually long-winded explanations, which I feel only contribute to the silliness. Simply put: In JavaScript, “this” refers to the object upon which a function is invoked. That’s it.

In JavaScript, “this” refers to the object upon which a function is invoked.

This means that “this” can only be used in a function, or globally. When used in either of these cases, “this” refers to the window object. When the function is a method of an object, then “this” refers to the object that the method is a member of. When the function is a constructor, then “this” refers to the instance object. There is much more to talk about with regards to what “this” means in varying scenarios, but these are the most common situations.

Example # 1

In Example # 1, we have added a property to the window object, named it: “music”, and assigned the value “classical”. In the line that follows, we output the value of “this.music”, and the result is: “classical”.

The reason for the output is simple: If you execute arbitrary code in the global context (i.e. outside of a function), then “this” refers to the window object. Executing arbitrary code in the global context is highly discouraged, but it is important to understand this behavior from a theoretical standpoint; in the global context: “this” will evaluate to the window object.

Example # 2

In Example # 2, we have added a function named foo, and then logged the output of that function’s execution. The resulting value is: “classical”. Some may have expected the output to be “blues”. This is a common mistake.

In the function “foo”, “music” is a variable. The “this” keyword has to do with objects, never variables (there is a very subtle scenario where “this” refers to a variable, which we will address in a later post). So the fact that there is a variable named “music” is completely meaningless in this example. The function “foo” does only one thing: it returns the value of this.music. In that function, “this” is the widow object, and the value of window.music is: “classical”. So, the variable “music” is completely ignored.

Example # 3

In Example # 3, we have added an object named “bar”. This object has two properties: “music”, which has a value of “jazz” and “getMusic”: a method that returns the value of bar’s “music” property.

The “getMusic” method has a line of code that you have seen in previous examples: “return this.music”. But why does that line of code return: “jazz”? The reason for this behavior is that when a function is a method of an object, the “this” keyword refers to the object upon which that function is invoked. In this case, the object is “bar”, and bar’s “music” property is equal to “jazz”, so “this.music” is equal to “jazz”.

Example # 4

In Example # 4, we have added the constructor function: “Baz”. “Baz” has a property named “music”, and it is equal to “rock”. It also has a property named “getMusic”, which is a method. The “getMusic” method returns the value of Baz’s “music” property.

You may be thinking that inside of the “Baz” constructor, the “this” keyword refers to the window object, as discussed in Example # 2. If we were to simply execute “Baz” (e.g. Baz() ), then yes, the property window.music would be overwritten and given the value of “rock”, and there would be a new global property named “getMusic”, which would return “rock”.

But that’s not what happens. After we create the constructor: “Baz”, we instantiate it, which results in a variable named “bif”, an instance of “Baz”. When you instantiate a JavaScript constructor function, the “this” keyword inside of that function refers to the instance object that the constructor returns.

HERE IS THE JS-FIDDLE.NET LINK

FOR EXAMPLE # 3:

Summary

In this article we discussed the high-level details of the JavaScript “this” keyword. We learned that it refers to the object upon which a function is invoked, and how it means different things in different scenarios. The scenarios we covered are: the window object, inside of a function, inside of a method, and inside of a constructor function.

Book Review: Node for Front-End Developers, by Garann Means

Node.js

Node for Front-End Developers, by Garann Means - CoverIf you are just getting started with server-side JavaScript, “Node for Front-End Developers” offers a fast, high-quality introduction.

The ubiquity of front-end JavaScript is undeniable. Not only has the appetite for web-based content increased dramatically, but so has the appetite for sophisticated user interfaces. More and more, visitors expect web-based content to offer complex interaction and high-performance. The explosion of mobile device use has only exacerbated this dynamic. Ryan Dahl’s Node.js turned the whole concept of JavaScript on its head by providing an open-source tool that allows the language to be leveraged on the server-side, significantly expanding the potential of this language.

Node for Front-End Developers, by Garann Means is a fast introduction to this incredibly powerful technology. The concept of creating a web-server provides a door through which clear and concise explanations present the basic concepts of server-side JavaScript. I found it particularly helpful that for such a short book, topics such as the query string, post data, path data routing, asynchronous events, templating, databases and MVC are well handled.

The book’s length is deceptive; readers will find a wealth of useful information here. While each topic represents a thread that deserves further reading, anyone who is new to Node.js will find Ms. Means’ introduction helpful. Her writing style is both relaxed and professional. From using NPM to install modules, to real-time communication with WebSockets, Node for Front-End Developers offers a range that is just enough to excite the reader, yet never too much detail. Any of the examples can be typed into your favorite text editor and fired-up with minimal effort. This is critical when delving into a new topic, and makes your introduction to Node.js disarming and fun.

  • Title: Node for Front-End Developers
  • Author: Garann Means
  • Publisher: O’Reilly Media
  • Date Published: February 7, 2012
  • Language: English
  • ISBN-10: 1449318835
  • ISBN-13: 978-1449318833

Angular 1.x Basics: Manually Boot-Strapping Your Application (Part II)

Angular

Angular JSOne of the advantages of manually boot-strapping Angular.js is the ability to take care of any setup-tasks that you want completed before the DOM is parsed.

In the previous article: “Angular.js Basics: Manually Boot-Strapping Your Application (Part I)“, we learned how simple it is to manually boot-strap Angular. In that example, our HTML was hard-coded in the page, including the {{myData}} template. We manually boot-strapped Angular by clicking a button, which in-turn, executed our boot-strapping code.

This was fine for a basic proof-of-concept, but having the {{myData}} template render on page load is not acceptable. For this article, our goal will be to inject some HTML into the DOM, and then boot-strap Angular, building upon our code from Part I of this series.

Example # 1:

In Example # 1, we leverage the angular.element() method, passing it a reference to the document object. We then chain the ready() method to the return value of the angular.element() method, passing it an anonymous function. This tells Angular that when the document is in a “ready” state, the anonymous function passed to the .ready() method should be executed.

Example # 2:

In Example # 2, we have added a few things:

1) The base DOM element that will contain HTML, managed by Angular (i.e. DIV#main)

2) A call to the angular.element() method, which sets up an anonymous function that will be called when the document is read

3) The bootAngular() function, which we have re-used from Part I of this series.

HERE IS THE JSFIDDLE LINK FOR EXAMPLE # 2: http://jsfiddle.net/T3jcx/

When you view the JsFiddle.net link for Example # 2, you’ll notice… well you’ll notice nothing! This is because there are no DOM elements for Angular to interact with. Although our code does, in fact, boot-strap Angular, Angular parses the DOM, but finds no “ng” directives or data-bound templates.

Example # 3A:

In Example # 3A, we have a string that contains HTML that will be injected into the page. The actual HTML is virtually identical to the markup from Part I of this series, but instead of hard-coding it in the actual web-page, it is contained in a string, which is a JavaScript variable: “template”.

Example # 3B:

In Example # 3B, we leverage the .run() method of our module. This is a method that we did not create, Angular provides it because our module (“myMod”), was created by Angular. We pass an anonymous function to the .run() method and this function takes the $rootScope object as an argument. A detailed discussion of the $rootScope object is beyond the scope of this article. But, it is helpful to know that it is the top-level container for all data managed by our module.

Inside of the anonymous function passed to the .run() method, we do two things:

1) Set the value of $rootScope.myData

2) Inject our HTML into the DOM

The most important thing to know is that when our module is instantiated, it’s .run() method is executed. So, we have specified what we want done when our module starts, which is to set the value of $rootScope.myData, and inject our HTML into the page.

Example # 4:

In Example # 4, we have the completed code. Comments have been added to help you follow along.

HERE IS THE JSFIDDLE LINK FOR EXAMPLE # 4: http://jsfiddle.net/w6Y3n/

How to Demo This Code:

Although it feels as if the HTML that contains the text box and {{myData}} template render on page load, they do not. Things happen pretty quickly here, but now that we have our completed code, and you have the JsFiddle.net link so that you can see the example code in action, let’s run-down what happens.

1) When the page loads, the BODY tag contains an empty DIV element with the ID: “main”

2) In the SCRIPT block, we create a variable named: “template”, which is a string containing HTML that will be injected into the page

3) We create the function: bootAngular(), which contains the code that boot-straps Angular

4) The angular.element() method is called, and then the ready() method is chained to the return value, and we execute the bootAngular() function as a result

5) Inside the bootAngular() function, we create an Angular module “myApp;” we call the myMod.run() method, which sets the value of $rootScope.myData, and then our HTML is injected into the DOM

6) We call the angular.bootstrap() method, which instantiates the myApp module, telling it to manage the BODY element in our page.

Summary:

In this article, we took a slightly more sophisticated approach to manually boot-strapping Angular. We leveraged the angular.element() method, which allows us to tell Angular to wait until the document is ready before proceeding, by using the .ready() method. We also learned about the [MODULE].fun() method, which provides a way to specify code that will execute when our module is instantiated. In the next article of this series, we will learn how to boot-strap multiple areas of the DOM manually.

 

Angular.js Basics: Manually Boot-Strapping Your Application (Part I)

Angular

Although setting an ng-app directive on the HTML element makes for quick and easy Angular.js boot-strapping, there may be times when you’ll want to initiate that process manually.

In an earlier blog post, we learned that boot-strapping an Angular Application is as simple as setting an ng-app directive on the HTML element, and then adding a script tag that will inject Angular.js into the page. Technically, we can set the ng-app directive on any element in the page, and we can even set it on multiple elements and provide the appropriate values for each directive, so that Angular knows which module will control which portion of the page.

While this kind of declarative architecture is both elegant and efficient, there may be times when you want to boot-strap Angular.js yourself. A common scenario might be one in which you want to have the initial web page render with no application-specific markup, inject the appropriate markup into the page, and then boot the application. This allows you to run any pre-application logic you need, and even decide on which markup to preset first, based on variable such as the URL path, the presence of a cookie, or some other condition.

While some might argue that this could be better handled by Angular Routes and Views, keep in mind that we are talking about tasks we want to run before Angular is even boot-strapped. So, the challenge is: “How can I boot-strap Angular.js manually?”

Fortunately, the process of boot-strapping Angular manually is fairly simple.

The Two Basic Steps Are:

1) Create an Angular module

2) Call the angular.bootstrap method, passing it two arguments: A) An element that the module will manage, and B) The name of the module that will manage that element (and all descendant elements)

Example # 1:

In Example # 1, we have the base HTML for our examples. For the sake of brevity, we are focusing on only the DOM elements that interest us. I’ll assume you understand that there are elements such as DOCTYPE, HTML HEAD and BODY, which make up a basic web page, as well as SCRIPT tags that inject jQuery and Angular, etc.

HERE IS THE JSFIDDLE LINK FOR EXAMPLE # 1: http://jsfiddle.net/mzcxQ/

When you view the JsFiddle.net link for Example # 1, you’ll see that although Angular was injected into the page using a SCRIPT tag in the HEAD section, it has not booted yet. This is evidenced by the fact that the {{myData}} template has not been parsed, and the actual curly braces appear in the page, which is not the desired effect. What we should see is an empty text box, and as you type in the textbox, whatever you have typed appears where the {{myData}} template is.

Example # 2:

In Example # 2, we create a variable named “myMod”. This variable will hold a new Angular module. We create the module by calling the angular.module method, and passing it two arguments:

A) The name of our module: ‘myApp’

B) An empty array

The empty array could be used for dependency injection, which is beyond the scope of this article. We don’t have any dependencies, but even so, the empty array is required.

Example # 3:

In Example # 3, we call the angular.bootstrap method, passing it two arguments:

A) The DOM element which will be managed by a module

B) The name of the module that will manage that element

In this example, we kept it simple and passed a reference to the BODY element, using jQuery. We could have specified the HTML element, or a more deeply-nested element in our page such as $(‘main .appContainer’), for example.

Example # 4:

In Example # 4, we have finally boot-strapped our Angular application. The combination of these two expressions was all that was needed in order to get Angular to start managing our DOM. To help emphasize the demonstration, we will wrap all of our code in a function, and execute that function when the button in our markup is executed.

Example # 5:

 

In Example # 5, we have wrapped all of our code in a function named: “bootAngular()”. We then created a click-event handler for the button in our markup (i.e. #bootAngular). When this button is clicked, the function bootAngular() is executed, and the button is disabled. When the bootAngular() function executes, our Angular boot-strapping code is executed, and Angular is boot-strapped.

HERE IS THE JSFIDDLE LINK FOR EXAMPLE # 5: http://jsfiddle.net/rvM4B/

How to demo this code:

When you view the JsFiddle.net link for Example # 2, you’ll notice that on page load, the {{myData}} template appears in the page. This is not what we want. It happens because while Angular has been injected into the page, it has not been boot-strapped. When you click the button labled: “Boot Angular”, our code executes, Anuglar is boot-strapped, the {{myData}} template disappears, and as we type in the text-box, whatever we type appears where the {{myData}} template was displayed. This is because Angular now manages that portion of the page. It has created a data-binding to the data: “myData” because it parsed the ng-model directive in the HTML, and whenever that data changes, the {{myData}} template is updated accordingly.

Summary:

In this article we learned how to manually boot-strap Angular. We learned how to create an Angular module, and then pass that module to the angular.bootstrap() method. We also learned that we pass a reference to the DOM element which we would like Angular to manage. This simple two-step process is all that is needed to boot-strap Angular. While the example provided is very basic, it illustrates the simplicity with which Angular can be manually boot-strapped.

 

 

Book Review: High Performance JavaScript by Nicholas C. Zakas

JavaScript

High Performance JavaScript by Nicholas C. Zakas Book Cover
High Performance JavaScript by Nicholas C. Zakas
While JavaScript engines are getting faster every day, complex logic or heavy DOM manipulation can still lead to sluggish browser performance. Nicholas C. Zakas takes you on a journey into the more subtle areas of JavaScript, providing a deeper understanding of how to create faster and more responsive user interfaces

For many front-end web developers, mastering concepts such as context, closures or callbacks is a major milestone in learning JavaScript. As you start to work with asynchronous events and complicated DOM manipulation, writing JavaScript code can become even more adventurous and quite rewarding. But it is right about this time that you may start to notice sluggish or even non-responsive pages. High Performance JavaScript (Build Faster Web Applications Interfaces), by Nicholas C. Zakas, provides numerous insights that will help you to understand why some of these issues arise and how to prevent them from happening.

With the help of Ross Harmes, Julien Lecomte, Steven Levithan, Stoyan Stefanov, and Matt Sweeney, Mr. Zakas leads the reader through a series of articles that detail advanced techniques for better JavaScript performance. In many cases, it comes down to programming patterns that are not unique to JavaScript, but lend themselves well to this context. But there is also JavaScript-specific advice with regard to cloning nodes, caching references to objects and optimizing expensive operations. Inside these 202 pages is expert advice on how to refactor loops, conditionals and recursion, as well as smarter regular expressions and AJAX. You’ll also find great coverage of the best tools available for improving JavaScript performance.

If you are an intermediate to advanced front-end web developer who is looking to gain a deeper understanding of the JavaScript language, this book is an invaluable resource.

  • Book Review: High Performance JavaScript by Nicholas C. Zakas
  • Length: 202 pages
  • Publisher: O’Reilly Media; 1st edition (March 30, 2010)
  • Language: English
  • ISBN-10: 059680279X
  • ASIN: B00CVDSYLG

Angular.js Basics: Routes Part III: Creating a Default Route (version 1.0.8)

Angular

Anuglar.js route

Learn how to create a default route in your Angular single-page app.

In Part II of this series: “Angular.js Basics: Routes Part II: Partials“, we learned how to leverage partials in order to decouple our HTML from the associated controllers. This not only proved to be fairly simple, but it also helps to keep our JavaScript code easier to manage and allows us to create HTML templates that can support a higher degree of complexity.

But in the previous example, when our page loaded, the element with the ngView directive was empty by default. So, the user was required to click a link in order for us to display any content provided by a partial.

In this article, we will learn about a new method of the $routeProvider object that allows us to tell Angular which partial to inject into the DOM when the base page loads.

Two things to note: 1) This article is specific to Angular 1.0.8.   2) The example code that follows leverages code from Part II of this series: “Angular.js Basics: Routes Part II: Partials“. For the sake of brevity, I won’t review much of what we learned in the previous article in great detail. If you are completely new to the idea of Angular Routes, I highly recommend you read Parts I and II of this series, and then return here.

You can download a working version of this code here: https://github.com/kevinchisholm/angular-1.0.8-default-route

The JavaScript file with the code samples you see below can be found in the file: www/js/myApp.js

Configuring your routes

Example # 1

In Example # 1, we re-visit the function expression: configFunction. You may recognize the two calls to $routeProvider.when(). These let angular know how we want it to handle requests to the routes “/hello” and “/goodbye”. In both cases, I’ve omitted the properties of the object that makes up the second argument to that method call, just to keep the example code to a minimum (these details were covered in Part I and Part II of this series).

The otherwise method

What follows those two calls is the .otherwise() method of the $routeProvider object. This method tells Angular what to do if the current request does not match any of the ones specified by the one or more calls we have made to the $routeProvider.when() method.

This is quite a useful feature. It allows us to continue to leverage an Angular partial that will be injected into the DOM by default. A typical scenario for this would be some kind of “home” page. Since the examples provided in this series are focused around the routes “/hello” and “/goodbye”, I decided that when neither route has been requested, I’d like to show the message “Hello!”. I’ve leveraged the same partial file: “message.html”, but the inline anonymous function that is assigned to the “controller” property sets the value of $scope.message” to “Welcome!”. The end result is that when you load the base page (i.e. part-3.html), the default message is “Welcome!”.

Example # 2

In Example # 2, we have added two hyperlinks to our navigation component: “Home” and “Bad Route”. The “Home” link simply requests an unspecified route: “#/”, which displays the default content “Welcome!”. We have specified this in the controller that is a property of the object passed to the $routeProvider.otherwise() method.

 

There is also a link named “Bad Route”, which requests the route: “/badroute”. Since we have not told Angular what to do when this route is requested, the details provided in our call to the $routeProvider.otherwise() method tells Angular to also display the default content: “Hello!”. But a subtle problem we have is the hash. In this case, the URL in the address bar will show: “#/badroute”, even though Angular does as we ask, and displays the default content. The problem here is that we are giving the user an opportunity to deep-link this URL, even though it is an un handled route. We need to fix this.

the redirect-to property

Example # 3

In Example # 3, we have added a new property to the object that is passed to the $routeProvider.otherwise() method: “redirectTo”. This tells Angular that when a route that we have not specified is requested, then in addition to using the specified partial and controller, it should re-direct the requested route to the “root” of our application. We could also specify another valid route, for example “/login”, etc. In this case, we simply want the address bar to show the root of the app. This way, when the user requests a route that is un handled, that request fails gracefully.

Example # 4

In Example # 4, we have the full code for our working example.

View and test the full working example code

HERE IS THE LINK FOR THE FULL WORKIG EXAMPLE: http://examples.kevinchisholm.com/javascript/angular/routes/part-3.html

How to Demo: In the blue box, you’ll notice two hyperlinks: “Hello” and “Goodbye”. Click either one of those links. When you click either link, you’ll notice that the appropriate HTML is injected into the DOM on the right side of the page. Note as well that in your browser’s address bar, “#hello” and “#goodbye” are appended to the URL. This is Angular’s way of providing support for deep-linking. The web page you are on never refreshes, but the hash portion of the URL changes.

Differences in the code

The main difference between this example and the same one from Part # 2 of our series is our use of a default route. When the page initially loads, the message “Welcome!” is displayed. The reason why this happens is: we have specified that message in our call to the $routeProvider.otherwise() method. Also, if you click the link: “Bad Route”, the default route is displayed as well. From Angular’s perspective, it is the exact same scenario: the user has requested a route that has not been specified, so our default route is used.

Summary

In this article, we learned how to create a default Angular.js route. While covering this topic, we focused on the the $routeProvider.otherwise method, which tells Angular how to handle a request for a route that has not been specified by a call to the $routeProvider.when() method. We also discussed the importance of the “redirectTo” property, which tells Angular to redirect to a route that has been properly configured, which makes for a better user experience.

here are some Helpful Links for the $routeProvider.otherwise method

http://docs.angularjs.org/api/ngRoute.$routeProvider

https://www.bitcast.io/b/getting-started-with-angularjs?v=angularjs-routeprovider-api

http://vxtindia.com/blog/8-tips-for-angular-js-beginners/

Angular.js Basics: Routes Part II: Partials

Angular

Angular.js LogoLearn how to use partial templates in your Angular single-page app.

In the first article of this series: “Angular.js Basics: Routes Part I,” we learned how Angular can intercept a hyperlink click, and inject HTML into the DOM. Accomplishing this is surprisingly straightforward because Angular provides a great deal of abstraction with regard to preventing a full-page refresh, DOM manipulation, and deep-linking via the hash.

In that previous post, the HTML that we injected into the DOM was a string that was assigned to the “template” property of the object passed to the $routeProvider.when() method. While this makes it easy to accomplish our task, it is not optimal because we are mixing with JavaScript. Also, a real-world scenario might require markup significantly more robust than the simple one-line string we use (i.e. <h1>{{message}}</h1>). What we need is the ability to leverage HTML that is separate from our JavaScript code, and could be hundreds, even thousands of lines of markup. Most importantly, our JS controller should have no concern for the markup we use; its only job is to be told where it is, and then inject it into the DOM.

An Angular partial is simply an HTML file. The main difference between this and a full-fledged web page is that the partial contains only the HTML we need. There is no need for a !DOCTYPE declaration, HTML, HEAD or BODY elements. The HTML in this file will be injected into the current web page, so only the markup that makes-up the actual component is needed.

Note: The example code that follows leverages code from Part I of this series: “Angular.js Basics: Routes Part I”. For the sake of brevity, I won’t review much of what we learned in the previous article in great detail. If you are completely new to the idea of Angular Routes, I highly recommend you read that article first, and then return here.

Example # 1

In Example # 1, we have the entire contents of the file message.html. This file sits in the same folder as our web page. As you can see, it contains only two lines of HTML: an H1 tag and a paragraph tag. There is also a set of double-curly-braces in the paragraph tag. As per our discussion in the last article, this is a placeholder for the “message” property of the $scope object to which this element is bound.

Example # 2

In Example # 2, we have our call to the $routeProvider.when() method. As per the previous article’s discussion, this method takes two arguments: the path that we want Angular to respond to, and an object that tells Angular how to handle this request.

The code in Example # 2 is virtually identical from that of the previous article with one exception: Instead of using a “template” property, we are now using a property named “templateUrl”. What this tells Angular is:

When the user requests “/hello”, do not actually direct the browser to that path.
Load the file “message.html” via ajax, and inject it into the DOM
In “message.html”, replace {{message}} with the value of $scope.message

While all of this occurs in virtually milliseconds, it is important to note that these steps are, in fact, executed by Angular.

Example # 3

In Example # 3, we have made the same change to the $routeProvider.when() method call for the path “/goodbye”.

Example # 4

HERE IS THE LINK FOR FULL WORKING EXAMPLE: http://examples.kevinchisholm.com/javascript/angular/routes/part-2.html

How to Demo: In the blue box, you’ll notice two hyperlinks: “Hello” and “Goodbye”. Click either one of those links. When you click either link, you’ll notice that the appropriate HTML is injected into the DOM on the right side of the page. Note as well that in your browser’s address bar, “#hello” and “#goodbye” are appended to the URL. This is Angular’s way of providing support for deep-linking. The web page you are on never refreshes, but the hash portion of the URL changes.

The main difference between this example and the same one from Part 1 of our series is our use of partials. Instead of hard-coding an HTML string in our JavaScript controller by assigning it to the ‘template” property, we specify a “templateUrl” property and assign a value that points to an HTML file containing only the markup we need.

Summary

In this article, we learned how to leverage Angular partials. Instead of hard-coding some HTML in our JavaScript file, we tell Angular where to find an HTML file that contains the markup we need. The main advantage here is the ability to decouple our JavaScript from the presentation code. And the HTML files that comprise our partials can be as large or complex as we like.

Helpful Links for Angular Partials

http://docs.angularjs.org/tutorial/step_07

http://onehungrymind.com/building-a-website-with-angularjs-routes-and-partials/

Angular.js Basics: Routes Part I

Angular

Learn how to spin-up an AJAX-driven single-page app by leveraging Angular.s Routes

Single-page applications have become a common project for many front-end web developers. The key components to any such endeavor is the ability to intercept hyperlinks, the updating of the DOM without actually refreshing the page, and support for deep-linking.

Anyone who has attempted even the most basic single-page application knows that managing this kind of interaction on the client-side can be tedious. Angular.js provides a significant level of abstraction when it comes to these kinds of tasks. In a few dozen lines of code, you can quite easily spin-up an AJAX-driven single-page app by leveraging Routes & Views.

Example # 1

In Example # 1, we have added the ng-app directive to the BODY tag. The value is “mainRouter”, which means there must be an Angular module by that name available. We will create this module shortly.

Example # 2

In Example # 2, we have two hyperlinks. Note that the values provided for each element’s HREF attribute are preceded by a hash. This allows Angular to intercept the hyperlink, process the request and prevent the page from following the URL (which would result in an error).

Example # 3

In Example # 3, we have an empty element with an ng-view directive. This is the element into which Angular will inject the HTML templates that we specify.

Example # 4

In Example # 4, we have created an Angular module. This is done by assigning a variable to the return value of a call to the angular.module() method. This method takes two arguments: the name of our module as a string (required), and an array of dependencies (optional). Although the second parameter is optional, because these dependencies are provided via an array, if you do not specify any dependencies, you must still include an empty array.

Example # 5

In Example # 5, we configure our router module by calling it the config() method. This method takes an array as an argument. The first element of the array is the $routeProvider object (which we will use shortly), and the name of a function that will execute our configuration code. It is perfectly acceptable (and quite common) to provide an inline anonymous function for the second parameter. I have specified a function expression instead, simply to keep the example code straightforward and easy to understand.

Example # 6

In Example # 6, we have a function named configFunction(). This function expression is passed to the config() method of our myRouter module. It takes the $routeProvider object as its sole argument. The real action takes place as we make a call to the $routeProvide’s when() method. This method expects two arguments: the URL to watch for, and an object. The properties of that object allow us to tell Angular a number of things about what should happen when the specified URL is requested by the user.

The specified URL is not a fully-qualified web address that starts with “http://”. Instead, we specify a path that is relative to the current page. The general approach is that this path should resemble a RESTful API address.

Examples:

  • http://www.some-domain.com/users (would return a list of users)
  • http://www.some-domain.com/users/1 (would return the user with the ID of “1”)
  • http://www.some-domain.com/users/add (would allow you to add a user)
  • http://www.some-domain.com/users/remove (would allow you to remove a user)
  • Etc…

A discussion of RESTful web services is out of the scope of this article. If you are not familiar with that topic, there are a few links at the bottom of this page that you might find helpful.

In the case of Example # 6, we have told Angular that when the user clicks a link that points to: “/hello”, two things should happen:

  1. The element with the ngView directive should have the HTML string assigned to the “template” property injected into it (i.e.<h1>{{message}}</h1>)
  2. The inline anonymous function that is assigned to the “controller” property should be executed.

A few things to note about these two actions that Angular takes:

In the HTML string that is injected into the element with the ngView directive, there is a set of double-curly-braces. This functions as a client-side template. When the specified HTML is injected into the DOM, the value of the “message” variable is inserted inside of that set of double-curly-braces. That value is provided by the function assigned to the “controller” property of this object passed to the $routeProvide’s when() method. That function takes the $scope object as an argument, and inside of the function, the string: “Hello!” is assigned to the “message” property of the $scope object.

Note: Once again, please note that this function expression could have been defined inline as an anonymous function when we made the call to myRouter.config() in Example # 5. The reason that I chose to break it out like that is because it made it easier to demonstrate the critical pieces of code, while keeping them fairly simple.

Example # 7

In Example # 7, we have added another route: “/goodbye”. So when the user requests that URL, the exact same actions taken in Example # 6 will be performed by Angular, with the only difference being the value of $scope.message: “GoodBye!”.

Example # 8

In Example # 8, we have the full code for our working example.

HERE IS THE LINK FOR OUR FULL WORKING EXAMPLE # 8: http://examples.kevinchisholm.com/javascript/angular/routes/part-1.html

How to Demo: In the blue box, you’ll notice two hyperlinks: “Hello” and “Goodbye”. Click either one of those links. When you click either link, you’ll notice that the appropriate HTML is injected into the DOM on the right side of the page. Note, as well, that in your browser’s address bar, “#hello” and “#goodbye” are appended to the URL. This is Angular’s way of providing support for deep-linking. The web page you are on never refreshes, but the hash portion of the URL changes. If you were to copy and paste http://examples.kevinchisholm.com/javascript/angular/routes/part-1.html#/hello or http://examples.kevinchisholm.com/javascript/angular/routes/part-1.html#/goodbye into another browser, your single-page app would “link” to that desired behavior. What is really happening is that Angular is intercepting any request that comes after the hash, and taking the actions that we specified in Examples # 6 and # 7. If you were to remove the hash from either URL, you would receive an error because the URL http://examples.kevinchisholm.com/javascript/angular/routes/part-1.html/goodbye is not valid.

Summary

In this article, we discussed Angular.js routes, a powerful feature that allows you to create fully-functioning single-page web apps with minimal effort. We talked about how to create an Angular module, configure that module, and call the $routeProvider.when() method in order to tell Angular how to intercept specific URL requests without refreshing the page, and inject the appropriate HTML into the DOM. We also discussed how this feature is based on RESTful URL syntax.

Helpful Links for Angular.js Routes and RESTful Web services

Angular.js Routes

http://docs.angularjs.org/api/ngRoute.$route

http://docs.angularjs.org/api/ngRoute

http://viralpatel.net/blogs/angularjs-routing-and-views-tutorial-with-example/

RESTful Web services

 

http://searchsoa.techtarget.com/definition/REST

http://www.ibm.com/developerworks/webservices/library/ws-restful/