Getting Started with Backbone.js Models – Part II : Creating an Initialize Method

Backbone

Backbone.js LogoIn the previous post: “Getting Started with Backbone.js Models – Introduction,” I discussed how the extend method of the Backbone.Model constructor is extended, which results in a new “class” that you can instantiate. When extending this constructor, an object was passed-in, which contained default values for the model data. Those default values were key/value pairs that were contained in the “defaults” property of the passed-in object.

In this post, we will talk about a sibling the of “defaults” property: the “Initialize” method.

The “Initialize” method

Why would we care about an Initialization method? Single page applications require an intimate relationship with the data. Not only do you consume and present data, but in many cases, you will want to know when a Backbone model is created or changed. Adding an “Initialize” method to your Backbone model allows you to interact with your model at the time of creation.

Why would I need an “Initialize” method?

While there are many answers to that question, a fairly typical one would be: “notification.” Let’s say that your single page application (aka “spa”), consumes a list of salespeople who work for a company, and presents that list in the DOM. If the application allows the user to create a new salesperson, then you would likely want to update the DOM, adding the new salesperson to the list. The most logical way to accomplish this is to have a method attached to your model that executes when a new instance is created (i.e. when the model constructor is instantiated), and that initialize method would update the DOM, possibly even presenting the data from this new model.

NOTE: In order to keep the code examples here short and simple, I will only present code that has changed since the last post. For the base code that is behind the working example below, view the page source as well as the link to the JavaScript file.

Example # 1A

Example # 1B

In Example # 1A, we have a quick re-cap of or SalesPerson Backbone model from the previous post. As discussed, we extend the Backbone.Model constructor, passing-in an object with a “defaults” property, which contains key/value pairs that supply default data values (e.g. “John” and “Smith”).

In Example # 1B, we have added a method named: “Initialize”. This method is executed when the model is instantiated. This means that every time we create a new model, that model’s “Initialize” method will execute. In this example, a message is logged to the console, which includes the “fname” and “lname” properties.

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

(be sure to open your JavaScript console when you view the JS Fiddle link above)

Example # 2

 

 

In Example # 2, we have the actual code from the full working example (link below). The reason for the setTimeout is to exaggerate the “message” effect. Since things happen pretty quickly, I wanted to make it a bit easier to see that when a new model is created, that model’s “initialize” method executes.

HERE IS THE LINK TO THIS ARTICLE’S FULL WORKING EXAMPLE: http://examples.kevinchisholm.com/backbone/models/basics/html/part-ii.html

How to Demo:

Each time a new SalesPerson item is created, a green message flashes in the upper-left-hand corner of the browser. When the page loads, there are four such messages. As you manually add new SalesPerson items, a green message will flash, showing the model data. All of this is made possible by the SalesPerson constructor’s initialize method.

Summary

In this post, we learned how to create an initialize method for a Backbone Model. We discussed why this is important, and how it can be used in a real-world context.

Helpful Links for Backbone Model’s initialize method

http://stackoverflow.com/questions/10118988/whats-the-difference-between-initialize-and-constructor-on-a-backbone-model

http://vairix.com/blog/backbone-initialize

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.