BACKBONE JS TUTORIAL PDF

adminComment(0)
    Contents:

To learn more about Leanpub, go to: resgoderfita.tk . Cross-domain resgoderfita.tk with sessions using CORS xxxvii. Security. BackboneJS is a light weight JavaScript library that allows to develop and structure client in this tutorial, please notify us at [email protected] To learn about the ideas behind resgoderfita.tk, you want to manage as few Getting resgoderfita.tk via npm, via a content delivery network (CDN) or from the .. whenever possible we provide it to you in five, DRM-free file formats—PDF,.epub .


Backbone Js Tutorial Pdf

Author:LILA MCGLOSTER
Language:English, Portuguese, Arabic
Country:Senegal
Genre:Religion
Pages:330
Published (Last):17.01.2016
ISBN:593-8-25801-642-1
ePub File Size:21.50 MB
PDF File Size:16.26 MB
Distribution:Free* [*Registration Required]
Downloads:22059
Uploaded by: CASSONDRA

JavaScript Application. Architecture with resgoderfita.tk JavaScript Conference Düsseldorf. Mathias Schäfer. 9elements. Full Stack JavaScript: Learn resgoderfita.tk, resgoderfita.tk and MongoDB PDF version and other digital versions like Mobi for site, the table of contents has local. BackboneJS Tutorial - Learn BackboneJS in simple and easy steps using this beginner's tutorial containing basic to advanced knowledge starting from Overview.

Main ; Backbone. History function. After the start method is triggered, the fragment attribute inside Backbone. It contains the value of the hash fragment. This sequence is helpful in managing the browser history according to the sequence of states. To direct the user to the previous state, click the back button of the browser. For a browser supporting pushState, Backbone will monitor the popstate event to trigger a new state.

If the browser doesn't support that HTML5 feature, the onhashchange event is monitored. If the browser does not support this event, a polling technique monitors any change on the hash fragment of the URL. Models and collections Models and collections are important components of Backbone. Models hold the data often coming from the server in key-value pairs.

To create a model, extend Backbone. Model, as in Listing 4. Listing 4. Model creation App. Team function is a new model function, but an instance of it must be created to use a specific model in an application, as in Listing 5.

Listing 5. Team ; The variable team1 now has the field named cid, which is a client identifier in the form of "c" plus a number for example, c0, c1, c2.

Models are defined by attributes that are stored in a hash map. Attributes can be set at instantiation time or with the set method. Attribute values are retrievable through the get method. Listing 6. One reason is for updating the value, as in Listing 7. Listing 7.

Updating attributes in a wrong way team1. Using set is the only way to change the state of the model and to trigger the change event on it. Using set promotes the principle of encapsulation. Listing 8 below shows how to bind an event handler to the change event. The event handler contains an alert that is triggered when the set method is called, as in Listing 6 , but is not triggered using the code in Listing 7.

Listing 8. Change event handler in the App. Team model App. Listing 9 shows an example. Listing 9. For subsequent attempts to send the object to the server, a PUT request is used. When a model needs to be retrieved from the server, a Read action is requested and an Ajax GET request is used. This type of request uses the fetch method. To determine the location on the server where the model data is pushed or pulled from: If the model belongs to a collection , the url attribute from a collection object will be the base of the location and the model ID not the cid will be appended to complete the full URL If the model is not inside a collection, the urlroot attribute of the model is used as the base of the location Listing 10 shows how to fetch a model.

Listing The validate method, which is triggered when the set method is called, needs to be overridden to contain the validation logic for the model. The only parameter passed to this function is a JavaScript object containing the attributes updated by the set method so conditions on those attributes can be verified. If nothing is returned from the validate method, the validation is successful. If an error message is returned, the validation fails and the set method will not execute. Validate method for a model App.

Collections are characterized by a model attribute defining the type of models composing the collection. Listing 12 shows how to create and populate a collection. Backbone collection App. Team ; teams. In a typical Ajax application, though, the collection will be populated dynamically not manually from the server. The fetch method helps accomplish the task, as in Listing 13 , and stores data into the array of models.

Fetch method teams. In some cases, to manipulate the raw data returned from the server, the parse method of a collection can be used, as in Listing The reset method is very handy for bootstrapping data into a collection, such as on page load, to avoid the user waiting for asynchronous calls to return.

If you are a developer looking to write code that can be more easily read, structured, and extended - this guide can help. Improving developer education is important to me, which is why this book is released under a Creative Commons Attribution-NonCommercial-ShareAlike 3.

This means you can download or grab a copy of the book for free or help to further improve it. Corrections to existing material are always welcome and I hope that together we can provide the community with an up-to-date resource that is of help. This book is targeted at novice to intermediate developers wishing to learn how to better structure their client-side code.

An understanding of JavaScript fundamentals is required to get the most out of it, however we have tried to provide a basic description of these concepts where possible. I am indebted to the fantastic work done by the technical reviewers who helped review and improve this book.

Their knowledge, energy, and passion have helped shape it into a better learning resource and they continue to serve as a source of inspiration. Thanks go out to:. I would also like to thank my loving family for their patience and support while I worked on this book, as well as my brilliant editor Mary Treseler. None of this work would have been possible without the time and effort invested by the other developers and authors in the community who helped contribute to it. I would like to extend my thanks to:.

Where possible, if you find using a newer version of Backbone breaks an example, please consult the official guide to upgrading as it contains instructions for how to work around breaking changes.

StackOverflow also contains many excellent examples of how other users are handling updating their code. I assume your level of knowledge about JavaScript goes beyond the basics and as such certain topics such as object literals are skipped. If you need to learn more about the language, I am happy to suggest:. You can however open the doors and windows toward the light as you see it. The goal of all architecture is to build something well; in our case, to craft code that is enduring and delights both ourselves and the developers who will maintain our code long after we are gone.

We all want our architecture to be simple, yet beautiful. Modern JavaScript frameworks and libraries can bring structure and organization to your projects, establishing a maintainable foundation right from the start. They build on the trials and tribulations of developers who have had to work around callback chaos similar to that which you are facing now or may in the near future.

When developing applications using just jQuery, the piece missing is a way to structure and organize your code. Backbone solves this problem for you, providing a way to cleanly organize code, separating responsibilities into recognizable pieces that are easy to maintain. A number of modern JavaScript frameworks provide developers an easy path to organizing their code using variations of a pattern known as MVC Model-View-Controller.

MVC separates the concerns in an application into three parts:. Views observe Models and update the user interface when changes occur. Some solutions including Backbone. It makes it easy to manage and decouple concerns in your application, leaving you with code that is more maintainable in the long term. Developers commonly use libraries like Backbone.

SPAs are web applications that load into the browser and then react to data changes on the client side without requiring complete page refreshes from the server. Backbone is mature, popular, and has both a vibrant developer community as well as a wealth of plugins and extensions available that build upon it.

Backbone focuses on giving you helpful methods for querying and manipulating your data rather than re-inventing the JavaScript object model. The entire Backbone source can be read and understood in just a few hours. These types of applications typically download a single payload containing all the scripts, stylesheets, and markup users need for common tasks and then perform a lot of additional behavior in the background. There certainly are complex Web applications where the partial rendering of views can be coupled with a single-page application effectively, but for everything else, you may find yourself better sticking to a simpler setup.

Has it become more effective at solving common problems? Does it continue to improve as developers build larger and more complex applications with it? Backbone provides a minimal set of data-structuring Models, Collections and user interface Views, URLs primitives that are helpful when building dynamic applications using JavaScript. You can either use the prescribed architecture it offers out of the box or extend it to meet your requirements.

While you are free to use the micro-templating offered by Underscore. Backbone also works quite well with other libraries, meaning you can embed Backbone widgets in an application written with AngularJS, use it with TypeScript, or just use an individual class like Models as a data backer for simpler apps.

There are no performance drawbacks to using Backbone to structure your application. It avoids run loops, two-way binding, and constant polling of your data structures for updates and tries to keep things simple where possible.

That said, should you wish to go against the grain, you can of course implement such things on top of it. This is made simpler by Backbone offering literate documentation of its source code, allowing anyone an opportunity to easily understand what is going on behind the scenes.

Having been refined over two and a half years of development, Backbone is a mature library that will continue to offer a minimalist solution for building better web applications. I regularly use it and hope that you find it as useful an addition to your toolbelt as I have. The goal of this book is to create an authoritative and centralized repository of information that can help those developing real-world apps with Backbone.

Chapter 2, Fundamentals , traces the history of the MVC design pattern and introduces how it is implemented by Backbone. Chapter 3, Backbone Basics , covers the major features of the Backbone.

Chapter 4, Exercise 1: Todos - Your First Backbone. Chapter 5, Exercise 2: Chapter 6, Backbone Extensions , describes Backbone. Marionette and Thorax, two extension frameworks which add features to Backbone. Chapter 7, Common Problems and Solutions , reviews common issues you may encounter when using Backbone. Chapter 9, Exercise 3: Paginator plugin to paginate data for your Collections. Chapter 12, Mobile Applications , addresses the issues that arise when using Backbone with jQuery Mobile.

Chapter 13, Jasmine , covers how to unit test Backbone code using the Jasmine test framework. A walkthrough of writing a Backbone-like library from scratch and other topics are also covered. Design patterns are proven solutions to common development problems that can help us improve the organization and structure of our applications.

By using patterns, we benefit from the collective experience of skilled developers who have repeatedly solved similar problems. MVC is an architectural design pattern that encourages improved application organization through a separation of concerns. It enforces the isolation of business data Models from user interfaces Views , with a third component Controllers traditionally managing logic, user-input, and coordination of Models and Views.

The pattern was originally designed by Trygve Reenskaug while working on Smalltalk , where it was initially called Model-View-Controller-Editor. An approach known as Separated Presentation began to be used as a means to make a clear division between domain objects which modeled concepts in the real world e.

The Smalltalk implementation of MVC took this concept further and had an objective of separating out the application logic from the user interface. The idea was that decoupling these parts of the application would also allow the reuse of Models for other interfaces in the application. A simple example of this is an application backed by stock market data - for the application to show real-time information, any change to the data in its Model should result in the View being refreshed instantly.

The web heavily relies on the HTTP protocol, which is stateless. This means that there is not a constantly open connection between the browser and server; each request instantiates a new communication channel between the two. Once the request initiator e. This fact creates a completely different context when compared to one of the operating systems on which many of the original MVC ideas were developed.

The MVC implementation has to conform to the web context. In Rails:. One reason for this is that Rails does not notify views from the model or controllers - it just passes model data directly to the view. That said, even for the server-side workflow of receiving a request from a URL, baking out an HTML page as a response and separating your business logic from your interface has many benefits.

This pattern layers an MVC stack behind a single point of entry. This single point of entry means that all HTTP requests e. The selected Controller Action takes over and interacts with the appropriate Model to fulfill the request. The Controller receives data back from the Model, loads an appropriate View, injects the Model data into it, and returns the response to the browser. This would return the blog article data from the database for editing. Finally, the resulting HTML response would be returned to the browser.

As you can imagine, a similar flow is necessary with POST requests after we press a save button in a form. Finally, if the user requested http: Within Index Action there would be a call to the Articles model and its Articles:: At that entry point, the Front Controller analyzes the request and, based on it, invokes an Action of the appropriate Controller. This process is called routing. The Model communicates with the data source e.

Once the Model completes its work it returns data to the Controller which then loads the appropriate View. The View executes presentation logic loops through articles and prints titles, content, etc. In the end, an HTTP response is returned to the browser. Several studies have confirmed that improvements to latency can have a positive impact on the usage and user engagement of sites and apps.

This is at odds with the traditional approach to web app development which is very server-centric, requiring a complete page reload to move from one page to the next. In addition to resulting in a great deal of duplicated content being served back to the user, this approach affects both latency and the general responsiveness of the user experience. A trend to improve perceived latency in the past few years has been to move towards building Single Page Applications SPAs - apps which after an initial page load are able to handle subsequent navigations and requests for data without the need for a complete reload.

Ajax Asynchronous JavaScript and XML makes communication with the server asynchronous so that data is transferred and processed in the background, allowing the user to interact with other parts of a page without interruption. This improves usability and responsiveness. SPAs can also take advantage of browser features like the History API to update the address seen in the location bar when moving from one view to another. These URLs also make it possible to bookmark and share a particular application state, without the need to navigate to completely new pages.

The typical SPA consists of smaller pieces of interface representing logical entities, all of which have their own UI, business logic and data. A good example is a basket in a shopping web application which can have items added to it.

This basket might be presented to the user in a box in the top right corner of the page see the picture below:. The basket and its data are presented in HTML. There was a time when we used jQuery or a similar DOM manipulation library and a bunch of Ajax calls and callbacks to keep the two in sync.

Backbone.js: Getting Started

That often produced code that was not well-structured or easy to maintain. Bugs were frequent and perhaps even unavoidable. The need for fast, complex, and responsive Ajax-powered web applications demands replication of a lot of this logic on the client side, dramatically increasing the size and complexity of the code residing there.

Eventually this has brought us to the point where we need MVC or a similar architecture implemented on the client side to better structure the code and make it easier to maintain and further extend during the application life-cycle.

Through evolution and trial and error, JavaScript developers have harnessed the power of the traditional MVC pattern, leading to the development of several MVC-inspired JavaScript frameworks, such as Backbone.

It will also need an HTML template containing a placeholder for a Todo item title and a completion checkbox which can be instantiated for Todo item instances. These are provided by the following HTML:. In our Todo application demo. Our Todo Model extends Backbone. Model and simply defines default values for two data attributes. As you will discover in the upcoming chapters, Backbone Models provide many more features but this simple Model illustrates that first and foremost a Model is a data container.

Prerequisite Content

TodoView is defined by extending Backbone. View and is instantiated with an associated Model. In our example, the render method uses a template to construct the HTML for the Todo item which is placed inside an li element. Each call to render will replace the content of the li element using the current Model data. Thus, a View instance renders the content of a DOM element using the attributes of an associated Model. Later we will see how a View can bind its render method to Model change events, causing the View to re-render whenever the Model changes.

So far, we have seen that Backbone. View implements the View. However, as we noted earlier, Backbone departs from traditional MVC when it comes to Controllers - there is no Backbone.

Instead, the Controller responsibility is addressed within the View. Recall that Controllers respond to requests and perform appropriate actions which may result in changes to the Model and updates to the View. In a single-page application, rather than having requests in the traditional sense, we have events. Events can be traditional browser DOM events e. While in this instance events help us relate Backbone to the MVC pattern, we will see them playing a much larger role in our SPA applications.

Event is a fundamental Backbone component which is mixed into both Backbone. Model and Backbone. View, providing them with rich event management capabilities. Note that the traditional controller role Smalltalk style is performed by the template, not by the Backbone. This completes our first encounter with Backbone.

The remainder of this book will explore the many features which build on these simple constructs. Once loaded, a client-side Router intercepts URLs and invokes client-side logic in place of sending a new request to the server. The picture below shows typical request handling for client-side MVC as implemented by Backbone:. The handlers update the DOM and Models, which may trigger additional events. Models are synced with Data Sources which may involve communicating with back-end servers.

The built-in capabilities of Models vary across frameworks. When using Models in real-world applications we generally also need a way of persisting Models. A Model may have multiple Views observing it for changes.

By observing we mean that a View has registered an interest in being informed whenever an update is made to the Model. This allows the View to ensure that what is displayed on screen is kept in sync with the data contained in the model.

Depending on your requirements, you might create a single View displaying all Model attributes, or create separate Views displaying different attributes. In Backbone, these groups are called Collections. Managing Models in groups allows us to write application logic based on notifications from the group when a Model within the group changes.

This avoids the need to manually observe individual Model instances. Collections are also useful for performing any aggregate computations across more than one model.

Users interact with Views, which usually means reading and editing Model data.

For example, in our Todo application, Todo Model viewing happens in the user interface in the list of all Todo items. Within it, each Todo is rendered with its title and completed checkbox.

We define a render utility within our View which is responsible for rendering the contents of the Model using a JavaScript templating engine provided by Underscore. We then add our render callback as a Model subscriber, so the View can be triggered to update when the Model changes. You may wonder where user interaction comes into play here. A Controller makes this decision.

It has long been considered bad practice and computationally expensive to manually create large blocks of HTML markup in-memory through string concatenation. Developers using this technique often find themselves iterating through their data, wrapping it in nested divs and using outdated techniques such as document. This approach often means keeping scripted markup inline with standard markup, which can quickly become difficult to read and maintain, especially when building large applications.

JavaScript templating libraries such as Mustache or Handlebars. These template blocks can be either stored externally or within script tags with a custom type e. Variables are delimited using a variable syntax e. JavaScript template libraries typically accept data in a number of formats, including JSON; a serialisation format that is always a string.

The grunt work of populating templates with data is generally taken care of by the framework itself. This has several benefits, particularly when opting to store templates externally which enables applications to load templates dynamically on an as-needed basis. One is implemented using the popular Handlebars. You may also use double curly brackets i. In the case of curly brackets, this can be done by setting the Underscore templateSettings attribute as follows:.

It is also worth noting that in classical web development, navigating between independent views required the use of a page refresh. In single-page JavaScript applications, however, once data is fetched from a server via Ajax, it can be dynamically rendered in a new view within the same page. As routers are neither a part of MVC nor present in every MVC-like framework, I will not be going into them in greater detail in this section.

In our Todo application, a Controller would be responsible for handling changes the user made in the edit View for a particular Todo, updating a specific Todo Model when a user has finished editing. So does Backbone. Not really. To summarize, the MVC pattern helps you keep your application logic separate from your user interface, making it easier to change and maintain both. Thanks to this separation of logic, it is more clear where changes to your data, interface, or business logic need to be made and for what your unit tests should be written.

Depending on how MVC has been implemented in a framework, it may also use the Factory and Decorator patterns. The observer-viewer nature of this relationship is what facilitates multiple Views being attached to the same Model. For developers interested in knowing more about the decoupled nature of MVC once again, depending on the implementation , one of the goals of the pattern is to help define one-to-many relationships between a topic and its observers.

When a topic changes, its observers are updated. Views and Controllers have a slightly different relationship. Having reviewed the classical MVC pattern, you should now understand how it allows developers to cleanly separate concerns in an application. You should also now appreciate how JavaScript MVC frameworks may differ in their interpretation of MVC, and how they share some of the fundamental concepts of the original pattern.

If you are interested in learning more about the variation of MVC which Backbone. Disqus chose Backbone. Offering a web app that aims to provide free world-class education to anyone anywhere, Khan Academy uses Backbone to keep its frontend code both modular and organized. MetaLab created Flow, a task management app for teams using Backbone. Its workspace uses Backbone to create task views, activities, accounts, tags and more.

Walmart chose Backbone to power its mobile web applications, creating two new extension frameworks in the process - Thorax and Lumbar. This boilerplate can be reused in many ways with little to no alteration and will allow you to run code from examples with ease. You can paste the following into your text editor of choice, replacing the commented line between the script tags with the JavaScript from any given example:.

You can then save and run the file in your browser of choice, such as Chrome or Firefox. Alternatively, if you prefer working with an online code editor, jsFiddle and jsBin versions of this boilerplate are also available. For Chrome, you can open up the DevTools via the Chrome menu in the top right hand corner: Next, switch to the Console tab, from where you can enter in and run any piece of JavaScript code by hitting the return key. Backbone models contain data for an application as well as the logic around this data.

For example, we can use a model to represent the concept of a todo item including its attributes like title todo content and completed current state of the todo. The initialize method is called when a new instance of a model is created. There are times when you want your model to have a set of default values e. This can be set using a property called defaults in your model. This method returns a copy of the attributes as an object not a JSON string despite its name. When JSON. The examples in the previous section took advantage of this feature when they called JSON.

Change events for each attribute are also triggered and can be bound to e. Models expose an. This is generally in the form of a JSON object similar to the model data you might find on the server but can take other forms.

Setting values through the. Instead they are silenced entirely:. Remember where possible it is best practice to use Model. If you want to receive a notification when a Backbone model changes you can bind a listener to the model for its change event.

A convenient place to add listeners is in the initialize function as shown below:. You can also listen for changes to individual attributes in a Backbone model. In the following example, we log a message whenever a specific attribute the title of our Todo model is altered.

Backbone supports model validation through model. Above, we also use the unset method, which removes an attribute by deleting it from the internal model attributes hash. Validation functions can be as simple or complex as necessary. If the attributes provided are valid, nothing should be returned from.

If they are invalid, an error value should be returned instead. This object is distinct from the current attributes of the model and from the parameters passed to the operation. Since it is created by shallow copy, it is not possible to change any Number, String, or Boolean attribute of the input within the function, but it is possible to change attributes in nested objects.

An example of this by fivetanley is available here. Note also, that validation on initialization is possible but of limited use, as the object being constructed is internally marked invalid but nevertheless passed back to the caller continuing the above example:.

This is usually achieved using JavaScript templating e. Creating a new view is relatively straightforward and similar to creating new models. To create a new View, simply extend Backbone. The central property of a view is el the value logged in the last statement of the example. What is el and how is it defined? There are two ways to associate a DOM element with a view: If you want to create a new element for your view, set any combination of the following properties on the view: A new element will be created for you by the library and a reference to it will be available at the el property.

If nothing is specified tagName defaults to div. The following example creates a ul element with id and class attributes:. If the element already exists in the page, you can set el as a CSS selector that matches the element. When declaring a View, options , el , tagName , id and className may be defined as functions, if you want their values to be determined at runtime. View logic often needs to invoke jQuery or Zepto functions on the el element and elements nested within it.

The view. If you need to apply an existing Backbone view to a different DOM element setElement can be used for this purpose. Overriding this. Our example will reference the following HTML markup:. The render method uses this template by passing it the toJSON encoding of the attributes of the model associated with the view. This populates the template, giving you a data-complete set of markup in just a few short lines of code.

A common Backbone convention is to return this at the end of render. This is useful for a number of reasons, including:. Simple enough. The ItemView could be written:. Note the usage of return this; at the end of render. This common pattern enables us to reuse the view as a sub-view. We can also use it to pre-render the view prior to rendering. The Backbone events hash allows us to attach event listeners to either el -relative custom selectors, or directly to el if no selector is provided.

An event takes the form of a key-value pair 'eventName selector': The only thing to really keep in mind is that any string callback supplied to the events attribute must have a corresponding function with the same name within the scope of your view.

Each of these callback functions can use this to refer to the TodoView object. The preceding example populated the collection using an array of models when it was instantiated. After a collection has been created, models can be added and removed using the add and remove methods:. Note that add and remove accept both individual models and lists of models.

There are a few different ways to retrieve a model from a collection. The most straight-forward is to use Collection. In client-server applications, collections contain models obtained from the server. In Backbone, this is done using the id , cid , and idAttribute properties. Each model in Backbone has an id , which is a unique identifier that is either an integer or string e.

Models also have a cid client id which is automatically generated by Backbone when the model is created. Either identifier can be used to retrieve a model from a collection. The idAttribute is the identifying attribute name of the model returned from the server i.

This tells Backbone which data field from the server should be used to populate the id property think of it as a mapper. By default, it assumes id , but this can be customized as needed. Internally, Backbone. Collection contains an array of models enumerated by their id property, if the model instances happen to have one.

When collection. As collections represent a group of items, we can listen for add and remove events which occur when models are added to or removed from a collection.

These can be clearer than needing three separate calls to. Backbone events also support a once method, which ensures that a callback only fires one time when a notification arrives.

Rather than adding or removing models individually, you might want to update an entire collection at once. If you need to simply replace the entire content of the collection then Collection.

Another useful tip is to use reset with no arguments to clear out a collection completely. This is handy when dynamically loading a new page of results where you want to blank out the current page of results. Note that using Collection. A reset event is fired instead as shown in the previous example.

The reason you might want to use this is to perform super-optimized rendering in extreme cases where individual events are too expensive. Also note that listening to a reset event, the list of previous models is available in options. This method attempts to perform smart updating of a collection using a specified list of models.

Models which are present in the collection but not in the list are removed. Backbone takes full advantage of its hard dependency on Underscore by making many of its utilities directly available on collections:. The complete list of what Underscore can do can be found in its official documentation. Chaining is a common idiom in object-oriented languages; a chain is a sequence of method calls on the same object that are performed in a single statement.

The chain method returns an object that has all of the Underscore array operations attached as methods which return that object. The chain ends with a call to the value method which simply returns the resulting array value. Some of the Backbone-specific methods do return this , which means they can be chained as well:. Thus far, all of our example data has been created in the browser. For most single page applications, the models are derived from a data store residing on a server.

This is an area in which Backbone dramatically simplifies the code you need to write to perform RESTful synchronization with a server through a simple API on its models and collections.

When this data is received, a set will be executed to update the collection. If the model is a new instance that was created in the browser i. A model can be removed from the containing collection and the server by calling its destroy method. Unlike Collection. Calling destroy on a Model will return false if the model isNew:. Most importantly, all methods accept success and error callbacks which can be used to customize the handling of server responses.

Events are a basic inversion of control. Instead of having one function call another by name, the second function is registered as a handler to be called when a specific event occurs. The part of your application that has to know how to call the other part of your app has been inverted.

This is the core thing that makes it possible for your business logic to not have to know about how your user interface works and is the most powerful thing about the Backbone Events system.

Note that Backbone. Events is mixed into the Backbone object. Since Backbone is globally visible, it can be used as a simple event bus:. Events can give any object the ability to bind and trigger custom events. Events provides a system that is very similar with on being analogous to subscribe and trigger being similar to publish. The callback is invoked whenever the event is triggered.

The official Backbone. A special all event is made available in case you would like notifications for every event that occurs on the object e. The all event can be used as follows:. To remove the dance event we previously bound to ourObject , we would simply do:. To remove all callbacks for the event we pass an event name e. If we wish to remove a specific callback, we can pass that callback as the second parameter:.

Finally, as we have seen in our previous examples, trigger triggers a callback for a specified event or a space-separated list of events. While on and off add callbacks directly to an observed object, listenTo tells an object to listen for events on another object, allowing the listener to keep track of the events for which it is listening. If you use on and off and remove views and their corresponding models at the same time, there are generally no problems.

For details on the topic and a solution, check this excellent article by Derick Bailey. Practically, every on called on an object also requires an off to be called in order for the garbage collector to do its job.

The default implementation of View. Within a View, there are two types of events you can listen for: It is important to understand the differences in how views bind to these events and the context in which their callbacks are invoked. Within callbacks bound using the events property, this refers to the View object; whereas any callbacks bound directly using jQuery will have this set to the handling DOM element by jQuery.

All DOM event callbacks are passed an event object by jQuery. See delegateEvents in the Backbone documentation for additional details. Event API events are bound as described in this section. If the event is bound using on on the observed object, a context parameter can be passed as the third argument.

If the event is bound using listenTo then within the callback this refers to the listener. The arguments passed to Event API callbacks depends on the type of event. See the Catalog of Events in the Backbone documentation for details. In Backbone, routers provide a way for you to connect URLs either hash fragments, or real to parts of your application. Any piece of your application that you want to be bookmarkable, shareable, and back-button-able, needs a URL.

An application will usually have at least one route mapping a URL route to a function that determines what happens when a user reaches that route.

This relationship is defined as follows:. This permits you to define routes such as http: Andrew de Andrade has pointed out that DocumentCloud, the creators of Backbone, usually only use a single router in most of their applications. Next, we need to initialize Backbone. The Backbone. By default, it simply updates your URL fragment without triggering the hashchange event:. It is also possible for Router. This usage is discouraged.

The recommended usage is the one described above which creates a bookmarkable URL when your application transitions to a specific state. We previously discussed how Backbone supports RESTful persistence via its fetch and create methods on Collections and save , and destroy methods on Models.

The inline Backbone. The sync function may be overridden globally as Backbone. Since all persistence is handled by the Backbone. The methodMap below is used by the standard sync implementation to map the method parameter to an HTTP operation and illustrates the type of action required by each method argument:.

If we wanted to replace the standard sync implementation with one that simply logged the calls to sync, we could do this:.

This can be safely tested separately, and potentially used with libraries other than Backbone. There are quite a few sync implementations out there. The following examples are all available on GitHub:. Router and DOM manipulation with Backbone. View, include json2. What this translates to is that if you require working with anything beyond models, you will need to include a DOM manipulation library such as jQuery or Zepto. Underscore is primarily used for its utility methods which Backbone relies upon heavily and json2.

In this chapter we have introduced you to the components you will be using to build applications with Backbone: Models, Views, Collections, and Routers. Finally, we saw how Backbone leverages the Underscore.

Backbone has many operations and options beyond those we have covered here and is always evolving, so be sure to visit the official documentation for more details and the latest features. In the next chapter you will start to get your hands dirty as we walk you through the implementation of your first Backbone application.

Essentially, these features are classic CRUD methods. In addition to the aforementioned dependencies, note that a few other application-specific files are also loaded. These are organized into folders representing their application responsibilities: An app. You will also need index. And remember that you can see a demo of the final application at TodoMVC. We will be creating the application JavaScript files during the tutorial.

To complete index. One way of including templates in the page is by using custom script tags. Underscore micro-templating can then access the templates, rendering fragments of HTML. In your own applications, you have a choice of template libraries, such as Mustache or Handlebars. The stats-template displays the number of remaining incomplete items and contains a list of hyperlinks which will be used to perform actions when we implement our router.

It also contains a button which can be used to clear all of the completed items.

Backbone.js For Beginners: Best Tutorials, Videos, And Learning Materials

The Todo model is remarkably straightforward. First, a todo has two attributes: These attributes are passed as defaults, as shown below:. Next, a TodoList collection is used to group our models. A nextOrder method implements a sequence generator while a comparator sorts items by their insertion order. Collection so that the reader knows how to find out more about them. Each view supports functionality such as edit-in-place, and therefore contains a fair amount of logic.

The element controller pattern consists of two views: In our case, an AppView will handle the creation of new todos and rendering of the initial todo list. Instances of TodoView will be associated with each individual Todo record. Todo instances can handle editing, updating, and destroying their associated todo. We will use this template later when we render our view. The two pieces of logic are:. When an add event is fired the addOne method is called and passed the new model. When a reset event occurs i.

We have added the logic for creating new todos, editing them, and filtering them based on their completed status. Allows a user to mark all of the items in the todo list as completed by clicking the toggle-all checkbox.

The initialize method completes by fetching the previously saved todos from localStorage. This will be in charge of individual Todo records, making sure the view updates when the todo does.

As a result, when the todo gets updated, the application will re-render the view and visually reflect its changes. Note that the model passed in the arguments hash by our AppView is automatically available to us as this. In the render method, we render our Underscore. In other words, the rendered template is now present under this.

So now we have two views: AppView and TodoView. The former needs to be instantiated on page load so its code gets executed. If you are following along, open file: In the console, add a new todo item: The newly created todo is also saved to Local Storage and will be available on page refresh. The todos added through the console should still appear in the list since they are populated from the Local Storage.

Also, we should be able to create a new todo by typing a title and pressing enter. The next part of our tutorial is going to cover completing and deleting todos. These two actions are specific to each Todo item, so we need to add this functionality to the TodoView view.

We will do so by adding togglecompleted and clear methods along with corresponding entries in the events hash. If you want to see an example of those, see the complete source. Finally, we move on to routing, which will allow us to easily filter the list of items that are active as well as those which have been completed.

When the route changes, the todo list will be filtered on a model level and the selected class on the filter links in the footer will be toggled as described above. When an item is updated while a filter is active it will be updated accordingly e.

The active filter is persisted on reload. TodoFilter to that string. As we can see in the line app. Finally, we create an instance of our router and call Backbone. The latest version of the full app can be viewed online at any time and the sources are readily available via TodoMVC. While our first application gave us a good taste of how Backbone.

In this exercise, we will build a library application for managing digital books using Backbone. For each book, we will store the title, author, date of release, and some keywords.

First, we need to create a folder structure for our project. To keep the front-end and back-end separate, we will create a folder called site for our client in the project root. Within it, we will create css, img, and js directories.

As with the last example, we will split our JavaScript files by their function, so under the js directory create folders named lib, models, collections, and views. Your directory hierarchy should look like this:.

We need a placeholder image for the book covers. We should also add in the HTML for the user interface. To see what this will look like with some data in it, go ahead and add a manually filled-in book to the books div. Not so great. This is not a CSS tutorial, but we still need to do some formatting. Create a file named screen. So this is what we want the final result to look like, but with more books.

Go ahead and copy the bookContainer div a few more times if you would like to see what it looks like. Now, we are ready to start developing the actual application.

These are both very simple, with the model only declaring some defaults:. Note that in the initialize function, we accept an array of data that we pass to the app. Library constructor. Finally, we have the entry point for our code, along with the sample data:.

Our app just passes the sample data to a new instance of app. LibraryView that it creates. When the user clicks the add button, we want to take the data in the form and use it to create a new model. In the LibraryView, we need to add an event handler for the click event:. Since we used the same names for ids in our form as the keys on our Book model, we can simply store them directly in the formData object.

We then create a new Book from the data and add it to the collection. We skip fields without a value so that the defaults will be applied. Backbone passes an event object as a parameter to the event-handling function. Adding a call to preventDefault on the event in the addBook function takes care of this for us. Now, we need to make a small detour and set up a server with a REST api. Since this is a JavaScript book, we will use JavaScript to create the server using node.

Download and install node. The node package manager npm will be installed as well. Download, install, and run MongoDB from mongodb. There are detailed installation guides on the website. Amongst other things, this file tells npm what the dependencies are for our project. On the command line, from the root of your project, type:. You should see npm fetch the dependencies that we listed in our package. We start off by loading the modules required for this project: Express for creating the HTTP server, Path for dealing with file paths, and mongoose for connecting with the database.

We then create an Express server and configure it using an anonymous function. Finally, we start the server by running the listen function. The port number used, in this case , could be any free port on your system. I simply used since it is unlikely to have been used by anything else.

We are now ready to run our first server:. This is where we left off in Part 2, but we are now running on a server instead of directly from the files. Great job! We can now start defining routes URLs that the server should react to.

Let us go back to server. The get function takes a URL as the first parameter and a function as the second. The function will be called with request and response objects. Now, you can restart node and go to our specified URL:. Now, since we want to store our data in MongoDB, we need to define a schema. Add this to server. As you can see, schema definitions are quite straight forward. They can be more advanced, but this will do for us.

I also extracted a model BookModel from Mongo. This is what we will be working with. The find function of Model is defined like this: The callback will be called with an error object and an array of found objects. If there was no error, we return the array of objects to the client using the send function of the response object. Otherwise, we log the error to the console. Restart node and go to localhost: Open up the JavaScript console.

Most other browsers will have a similar console.

In the console type the following:. The returned array is obviously empty, since we have not put anything into the database yet. We start by creating a new BookModel, passing an object with title, author, and releaseDate attributes. The data are collected from request. Actually, the caller can omit any or all attributes since we have not made any of them mandatory.

We then call the save function on the BookModel passing in a callback in the same way as with the previous get route. Finally, we return the saved BookModel. Restart node and go back to the console and type:.

The object we get back, however, contains a JavaScript Date object. Here, we use colon notation: We also use the findById function on BookModel to get a single result. If you restart node, you can get a single book by adding the id previously returned to the URL like this:.

This is a little larger than previous ones, but is also pretty straight forward — we find a book by id, update its properties, save it, and send it back to the client. To test this, we need to use the more general jQuery ajax function. Again, in these examples, you will need to replace the id property with one that matches an item in your own database:. Well, until now I have left out the keywords part of our books.

To do that, we need another schema. Add a Keywords schema right above our Book schema:.This is at odds with the traditional approach to web app development which is very server-centric, requiring a complete page reload to move from one page to the next.

The Backbone extensions Marionette and Thorax provide logic for nesting views, and rendering collections where each item has an associated view. Backbone passes an event object as a parameter to the event-handling function.

But I wonder if there is a cohesive method yet of using javascript everywhere. Far too many for me to write about individually. Events such as change, add, remove.