Getting Started with Backbone.js Views – Part III : Event Handlers Basics

Backbone

Backbone.js LogoLearn how to set up event handlers in your Backbone.js view

In the previous two articles of this series: “Getting Started with Backbone.js Views” (Parts I & II), we learned how to set up a view and optimize it for better performance. The next logical step is event handlers.

While it may be possible that your view will not be interactive, it’s difficult to imagine a mature application that does not involve event handlers. Backbone’s approach to event handlers is a bit of a departure from your standard document.addEventListener and jQuery.click methods. Here, you will add an “events” property to the object that is passed into the Backbone.View.extend method. That “events” property is an object whose key-value pairs are sets strings comprised of an event/selector and event handler.

Example # 1A

In Example # 1A we have instantiated the MessageView constructor. Implementation details of our Backbone.js router are not at all the focus of this article, but I wanted to point out that when setting up event handlers in a Backbone view, it is important to pass an object to the view constructor. In that object, we have specified an “el” property, whose value is a jQuery DOM object. The reason for this is that it allows Backbone to properly attach our event handlers and then tear down the views DOM elements change.

Example # 1B

In Example # 1B we have added an “events” property to the object that is passed into the Backbone.View.extend method. This property is an object. In this example, that object has one property. The property name is a string that consists of two parts: the name of the event, followed by a CSS selector that identifies the DOM element to be targeted. In this case, the “click” event is specified, and the following CSS selector targets the element: “.messageView.mainMessage p”. Again, that is the key or property name. The value of that property is: “clickHandler“, the name of the function that will handle the event. This example is not very exciting. When the target element is clicked an alert shows the message: ‘I was clicked!’. We can do better.

Example # 1C

In Example # 1C, we inject the message: “I was clicked” into the DOM, a step up from the alert, but still not too sophisticated. We’ll clean this up in Example # 3.

Example # 2

In Example # 2, we have added two more properties to the “events” object: mouseover and mouseout event handlers. The purpose of this example is to illustrate that you can specify as many event handlers as you need in your “events” object.

Obtaining a Reference to the Target Element

Example # 3

In Example # 3, we have set up some functionality that is a bit of an improvement over the alert in Example # 1. Each time you click the message, timestamp is injected into the page.

You’ll notice that we are using a function named: “renderTimestamp”. This function is defined in the HTML file. Its implementation details are not particularly important. Suffice to say that when passed a jQuery DOM element object, it injects a time-stamped child element. The purpose of this is simply to demonstrate that we have real-time access to whichever DOM element is the target of an event.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://examples.kevinchisholm.com/backbone/views/basics/html/part-iii.html

How to Demo:

When the page loads, you will see the default route. If you click “message/hello” or “message/goodbye”, you’ll see our custom routes in action. In either case, the message text has a click handler attached to it.

When you click the message text, you will see a time-stamp injected into the page. No matter how many times you click the message a new time-stamp will be added. When you mouse-over any time-stamp, the background color of that time-stamp will change.

Summary

In this article we learned the basics of how to set up event handlers in a Backbone.js view. We discussed how to specify the “el” property for a view, and then create an “Events” object. We also covered how to configure multiple events, as well as how to reference the target element and manipulate it.

Helpful Links for Backbone.js View Events

http://www.codebeerstartups.com/2012/12/12-listening-to-dom-events-in-backbone-js-learning-backbone-js

http://kevinhamiltonsmith.com/backbone-js-view-dom-events-complete-list/

http://lostechies.com/derickbailey/2011/11/09/backbone-js-object-literals-views-events-jquery-and-el/

Getting Started with Backbone.js Views – Part II : Optimization Basics

Backbone

Backbone.js LogoiLearn how to optimize your Backbone.js view for better performance

In the first part of this series:  Getting Started with Backbone.js Views – Part I : Introduction, we learned the basics of how to implement a view in Backbone.js. Although the process of extending the Backbone.View class was quite similar to extending the Backbone.Route constructor, our code was not efficient. There are two areas to address: 1) Multiple constructor instantiations, and 2) Separation of presentation and data.

Multiple constructor instantiations

Example # 1A

In Example # 1A, we have the “message” method that is meant to handle any request to the “#/message/:text” route. While this method works as intended, we instantiate the the “MessageView” class each and every time that route is requested. There is no reason to instantiate that class more than once, and from a performance standpoint, this code is inefficient.

Example # 1B

In Example # 1B, we’ve fixed the instantiation problem by leveraging the “initialize” method. If you remember from the article: “Getting Started with Backbone.js Routes – Part IV: Configuring an Initialization Function”, the “initialize” method only executes once. This is a perfect place to handle setup tasks for views. In Example # 1B, we instantiate the “MessageView” constructor. But, instead of assigning the newly instantiated object to a variable, we assign it to “this”, which is the instance of the “AppRouter” constructor. The reason we do this is because we will need access to that instance object from the “message” method.

Then, in the “message” method, we reference that instance object twice: when setting its “options.message” property and then when calling its “render” method. Both of those actions happen every time the “#/message/:text” route is requested.

Example # 2A

In Example # 2A, we can see the other problem with our code: we mix JavaScript in with our HTML. While this does work, but it is not the most efficient way to go, and we are mixing presentation with data. We will fix this by using Handlebars.js.

Example # 2B

In Example # 2B, we have replaced our “template” method with a call to the Handlebars.compile method. We pass it our string of HTML with one small but important change: the double-curly-braces templating syntax: {{message}}. A discussion of JavaScript templating is beyond the scope of this article, but it is important to note that by using Mustache.js (or a similar templating library), we do not need to mix-in JavaScript with the HTML string we pass to the Handlebars.compile method. The double-curly-braces templating syntax: {{message}} safely retrieves the data that we reference.

Example # 3

In Example # 3, we have the full code for our working example. Visually there is nothing going on in Example # 3 that you have not seen already in an earlier article. But if you look at the page source, you’ll see that there is a dramatic difference in how we go about instantiating the MessageView constructor, as well as how we reference the data in our view’s “template” method.

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

How to Demo:

This example will not appear to work any differently from the previous article’s examples. The important thing to note is what is going on under the hood. Take a look at the JavaScript file for Example # 3, so you can see that we have put the techniques discussed into action.

http://examples.kevinchisholm.com/backbone/views/basics/js/part-ii.js

Summary

In this article we learned two important optimization techniques for Backbone.js views: instantiating the view constructor only once, and separating the presentation from logic. We discussed the router’s “initialize” method as the best place to instantiate our view constructor, as well as how to use the JavaScript “this” keyword to make that instance object available to other methods in the Router class. We also learned how to leverage Mustache.js for client-side templating.

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

Backbone

Backbone.js LogoLearn how to separate presentation from logic by leveraging Backbone.js views2

One of the main principles of MVC is the separation of presentation, data and logic. While it may be tempting to mix these concerns in order to “get it out the door”, maintaining and extending this kind of code can quickly become a nightmare. In this article, we will be introduced to Backbone.js views, which provide a tremendous amount of abstraction that keeps presentation separate from logic.

In the previous articles about Backbone routes, we learned about extending Backbone classes. Specifically, we discussed extending the Backbone.Route class. When it comes to leveraging Backbone views, the approach is exactly the same. The only difference is that we will extend the Backbone.View class.

Example # 1A

In Example # 1A, we create a variable named MessageView. This variable will become a constructor function that inherits from the Backbone.View class. We accomplish this by using the extend method of the Backbone.View class. In very much the same way that we extended the Backbone.Route class, we pass an object to the Backbone.View.extend method. In this example, the object that we passed in has two properties: “template” and “render”.

The Template Property

The “template” property tells the view “what” to render. That is, it provides the actual HTML that will be injected into the DOM. This property must be a function. Since it is a property of an object, that makes it a method. Even though it ultimately provides a string of HTML, it must be a function. So we have made it a function that returns a string of HTML.

The Render Method

The “render” property is a function, which makes it a method. This method is where you provide the code that injects the template property’s HTML into the DOM. Let’s break down the code in this method:

this.$el – “this” refers to the object, which is the instance of the MessageView variable (which is a class that we created, and it extends, or inherits from the Backbone.View class). The Backbone.View class provides a property named: “$el”, which is a jQuery object that represents the view’s parent element.

this.$el.html – Since “$el” is a jQuery object, we can use its “html” method to inject markup into the DOM.

this.template – Refers to the “template” property that we discussed above (and don’t forget: that “template” property is a method).

Example # 1B

In Example # 1B, we have the the full JS code that is used in the working example URL (below). We are leveraging what we learned about Backbone.js routes but creating a route, and configuring it for a “default” route, and our “message” route. So, when the user chooses a “message” route (e.g. “#/message/hello” or “#/message/goodbye”), our “MessageView” class is instantiated.

But this example falls short in one pretty big way: our “message” route takes a parameter from the user, but we are not making any use of that in in the view. Let’s fix this.

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

How to Demo:

When the page loads, you will see the message: “This is the default route”. If you click either of the other two nav links, you will see the message: “Hello from the MessageView class!”. This markup is injected into the DOM by our MessageView class.

Example # 2

In Example # 2, we made two changes:

1) we use the “text” argument passed-into the “message” method that handles the “#/message:text” route. We get this information to the view in the following line:

view.options.message = text ? text : ‘No Message Provided!’;

Details: We use a ternary operator so that if there is no text parameter passed-in, we have a default message to provide to the view.

2) We inject the message into the view’s HTML in the following line:

‘The message is: ‘ + this.options.message + ‘

Details: In the HTML string that we are returning from the view’s “template” method, we reference the “message” property of the view’s “options” object.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://examples.kevinchisholm.com/backbone/views/basics/html/part-i-ex2.html

How to Demo:

When the page loads, you will see the message: “This is the default route”. If you click either of the other two nav links, you will see the message: “The message is: hello” or “The message is: goodbye”. This is because the “message” route passes the “text” parameter to the view as the “message” property of its “options” object.

Summary

In this article, we had a brief introduction to Backbone.js views. We learned how to extend the Backbone.View class, and create the HTML that will be injected into the DOM. We also learned how to pass parameters to the view so that it can be dynamic.

Getting Started with Backbone.js Routes – Part IV: Configuring an Initialization Function

Backbone

Backbone.js LogoLearn how to configure a function that initializes your Backbone.js router

In the last few articles of this series, we have learned the basics of setting up routes in Backbone.js. We’ve discussed setting up route handlers, specifying a default route, graceful actions for corner-cases, as well as passing parameters to routes. But what about setup tasks? Sometimes you may want to execute code in preparation for your routes, but these tasks need to be completed before the routes are activated.

In this article, we will learn how to set up an initialization function that will run once, and is guaranteed to do so before the router is started.

Like much of what we have already discussed with regards to Backbone, this functionality is fairly straightforward. In the object that we pass to the Backbone.Router.Extend method, we provide an “initialize” property, which will be a method.

NOTE: In the code examples that follow, I have removed most of the implementation code so that the example will be shorter and easier to follow.

Example # 1

In Example # 1, we have added a property that is passed-into the Backbone.Route.extend method. This property is named: “initialize” and it is a method. This method will execute before the router is started. In this example, we simply fade-in a message, letting the user know that the router is initialized.

HERE IS WORKING CODE LINK FOR EXAMPLE # 1:

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

Example # 2

In Example # 2, we’ve upgraded our initialize method a bit. First, we moved all of the initialization code to the function: domSetup, just to keep the example code short and simple. There is no need to discuss the domSetup function in detail; it simply fades-in a message and sets up a few click handlers.

What interests us is the functionality that is provided here. Notice that when the page loads, if you click any of the nav links, nothing happens. This is because the router has not not been started yet. I have set a five-second timeout that delays the router’s start (the AJAX loader gif is spinning during this timeout). Once you see the green message fade-in, then all of the nav element clicks will work.

The point here was to demonstrate that if you have tasks you’d like to complete before the router is started, you can safely queue them up inside of the “initialize” method.

HERE IS WORKING CODE LINK FOR EXAMPLE # 2: http://examples.kevinchisholm.com/backbone/routes/basics/html/part-iv-ex2.html

How to Demo:

When the page loads, notice that there is an AJAX loader gif. As long as you see that AJAX loader, none of the nav element links work. Once the AJAX loader goes away and the message in a green box fades in, the nav links will work as expected. What is being demonstrated here is the fact that you can execute any setup code from the “initialize” method and then start the router manually as you wish. This is accomplished in the example code by placing all of the code that sets up the delay in the “initialize” method.

Summary

In this article, we learned how to set up an initialization function for a Backbone.js router. We learned about the “initialize” property of the object that we pass into Backbone.Router.extend, as well as how to manually start the router once our setup tasks have completed.

Getting Started with Backbone.js Routes – Part III: Passing Parameters to the Route

Backbone

Backbone.js LogoLearn how to pass values to your Backbone router in the URL

In the second part of this series: Getting Started with Backbone.js Routes – Part II: Handling Bad Requests, we learned how to handle route requests that are not configured in our router. This allows us complete control over the user experience, even when the request is one we had not anticipated. But what about parameters? How can we send the router a message? In other words, how can we pass a value in the URL that tells the application something specific?

In this article, we will learn how to pass parameters to the router, and in turn, how to access the values that are passed-in. So, for the examples that follow, we’ll imagine a very simple “order” page which allows you to specify the item you want to order in the URL. In order to keep the examples brief, I have removed any code that is not germane to the current discussion. But the full JS source code URL will be provided with each link to the working demo.

Example # 1

In Example # 1, we’ve set up a route named: “order/:item”. Up until now, our route names have been a single or hyphen-separated word. This new syntax, however, allows for more functionality.

Notice that in the route’s name, there is a colon. That colon tells Backbone that what follows is a parameter. So in this case, the actual route is “order/” and “:item” is a placeholder for whatever the user provides in that part of the URL. That value is an unknown, so we use the word “item” to represent this unknown value.

This route is handled by the method: “route”. Notice that the “route” method takes one argument: “item” (we could have named it anything, but I used “item” just to keep things consistent). This represents the parameter that was provided in the URL. So, inside of the “order” method, we now have access to that parameter.

HERE IS THE WORKING DEMO LINK FOR EXAMPLE # 1: http://examples.kevinchisholm.com/backbone/routes/basics/html/part-iii-ex1.html

HERE IS THE LINK FOR EXAMPLE # 1’s JavaScript: http://examples.kevinchisholm.com/backbone/routes/basics/js/part-iii-ex1.js

How to Demo:

Below the main nav is a brown navigation menu. As you click each menu item, notice that the URL changes. For example: “#/order/chair” or “#/order/shirt”. So, with each click, the message in the page will reflect the parameter passed in the URL after “#/order/”. You can enter whatever you like after “#/order/”, and that value will be reflected in the page’s message.

But what if the user wants to order more than one item?

Yes! This is a very logical feature to implement. It is common to specify a quantity when you order something. So, we’ll need to adjust our router so that the user can also provide the quantity in the URL in addition to the item name.

Example # 2

In Example # 2, we’ve added a new route: “order/:item/:count”. This route is also handled by the “order” method. There are two changes. This new route allows for a “count” parameter (i.e. “:count/”), and the “order” method takes a second argument: “count”.

Inside of the “order” method, we have updated the message that is injected into the DOM to include the “count” parameter, or the quantity of items to be ordered.

HERE IS THE WORKING DEMO LINK FOR EXAMPLE # 2:

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

HERE IS THE LINK FOR EXAMPLE # 1’s JavaScript:

http://examples.kevinchisholm.com/backbone/routes/basics/js/part-iii-ex2.js

How to Demo:

Below the main nav is a brown navigation menu. As you click each menu item, notice that the URL changes. For example: “#/order/chair/1” or “#/order/shirt/2”. With each click, the message in the page will reflect the parameter passed in the URL after “#/order/”, as well as the quantity (i.e. “#/order/quantity”).

But now we have a problem: If the user enters ““#/order/item” but does not specify a quantity, then the quantity will show up in the DOM as “undefined”. That’s not a good user experience, so let’s handle that exception.

Example # 3

In Example # 3, we’ve made two adjustments to our code. First, we’ve added a new route: “order/:item/”, which is handled by the “order” method. Second, we’ve added a quick check at the top of the “order” method: if (!count){count = 1}. This tells the “order” method: “hey, if the count argument is 0 or is not provided, then just make the quantity: 1).

HERE IS THE WORKING DEMO LINK FOR EXAMPLE # 3:

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

HERE IS THE LINK FOR EXAMPLE # 3’s JavaScript:

http://examples.kevinchisholm.com/backbone/routes/basics/js/part-iii-ex3.js

How to Demo:

Below the main nav is a brown navigation menu. As you click each menu item, notice that the URL changes. For example: “#/order/chair” or “#/order/shirt/”. Note that in the case of the first two links there is no quantity provided. In both cases, our “order” method sets the quantity to: 1.

Summary

In this article we learned how to pass parameters to a Backbone.js route. We learned the syntax needed to specify which part of the route request is the actual route and which part is the parameter. We discussed how to access that parameter in the function that handles the route request, how to allow for multiple parameters, and how to handle corner cases where an expected parameter is not provided.

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.

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.