BackboneJS - Tutorialspoint

2y ago
3 Views
2 Downloads
1.04 MB
16 Pages
Last View : 1m ago
Last Download : 2m ago
Upload by : Harley Spears
Transcription

BackboneJSi

BackboneJSAbout the TutorialBackboneJS is a light weight JavaScript library that allows to develop and structure clientside applications that run in a web browser. It offers MVC framework which abstracts datainto models, DOM (Document Object Model) into views and bind these two using events.This tutorial covers most of the topics required for a basic understanding of BackboneJSand to get a feel of how it works.AudienceThis tutorial is designed for software programmers who want to learn the basics ofBackboneJS and its programming concepts in simple and easy ways. This tutorial will giveyou enough understanding on various components of BackboneJS with suitable examples.PrerequisitesBefore proceeding with this tutorial, you should have a basic understanding of HTML, CSS,JavaScript, and Document Object Model (DOM). As we are going to develop a web-basedapplications using BackboneJS, it will be good if you have an understanding of how webbased applications work in general.Copyright & Disclaimer Copyright 2016 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of Tutorials Point (I)Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republishany contents or a part of contents of this e-book in any manner without written consentof the publisher.We strive to update the contents of our website and tutorials as timely and as precisely aspossible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of ourwebsite or its contents including this tutorial. If you discover any errors on our website orin this tutorial, please notify us at contact@tutorialspoint.comi

BackboneJSTable of ContentsAbout the Tutorial . iAudience . iPrerequisites . iCopyright & Disclaimer . iTable of Contents . ii1.BackboneJS – Overview . 12.BackboneJS – Environment Setup . 33.BackboneJS – Applications . 74.BackboneJS – Events . 10BackboneJS –Event On . 10BackboneJS – Event Off . 12BackboneJS – Event Trigger . 14BackboneJS – Event Once . 15BackboneJS – Event listenTo . 17BackboneJS – Event stopListening . 18BackboneJS – Event listenToOnce . 20Catalog of Built-in Events . 225.BackboneJS – Model . 24BackboneJS – Model Extend . 27BackboneJS – Model Initialize . 28BackboneJS – Model Get . 29BackboneJS – Model Set . 30BackboneJS – Model Escape . 31BackboneJS – Model Has . 32BackboneJS – Model Unset . 34BackboneJS – Model Clear. 35BackboneJS – Model Id . 37BackboneJS – Model IdAttribute . 38BackboneJS – Model Cid . 39BackboneJS – Model Attributes. 40BackboneJS – Model Changed . 41BackboneJS – Model Defaults . 43BackboneJS – Model toJSON . 44BackboneJS – Model Sync . 45BackboneJS – Model Fetch . 47BackboneJS – Model Save . 48BackboneJS – Model Destroy . 49BackboneJS – Model Validate. 51BackboneJS – Model validationError . 53BackboneJS – Model isValid . 54BackboneJS – Model Url . 56BackboneJS – Model urlRoot . 57BackboneJS – Model Parse . 58BackboneJS – Model Clone . 60BackboneJS – Model hasChanged . 61ii

BackboneJSBackboneJS – Model isNew . 62BackboneJS – Model changedAttributes . 63BackboneJS – Model Previous . 65BackboneJS – Model previousAttributes . 66Underscore Methods . 676.BackboneJS – Collection . 69BackboneJS – Collection Extend . 71BackboneJS – Collection Model . 73BackboneJS – Collection Initialize . 75BackboneJS – Collection Models . 77BackboneJS – Collection toJSON . 79BackboneJS – Collection Sync . 80BackboneJS –Collection Add . 82BackboneJS – Collection Remove . 84BackboneJS – Collection Reset . 86BackboneJS – Collection Set . 88BackboneJS – Collection Get . 90BackboneJS – Collection At. 91BackboneJS – Collection Push . 93BackboneJS – Collection Pop . 95BackboneJS – Collection Unshift . 97BackboneJS – Collection Shift . 99BackboneJS – Collection Slice . 101BackboneJS – Collection Length . 102BackboneJS – Collection Comparator . 104BackboneJS – Collection Sort. 106BackboneJS – Collection Pluck . 107BackboneJS – Collection Where . 109BackboneJS – Collection findWhere . 111BackboneJS – Collection Url . 113BackboneJS – Collection Parse . 115BackboneJS – Collection Clone . 117BackboneJS – Collection Fetch . 118BackboneJS – Collection Create. 120Underscore Methods . 1227.BackboneJS – Router. 125BackboneJS – Router Extend . 125BackboneJS – Router Routes . 128BackboneJS – Router Initialize . 130BackboneJS – Router Route . 132BackboneJS – Router Navigate . 134BackboneJS – Router Execute. 1378.BackboneJS – History . 141start . 1419.BackboneJS – Sync. 144Backbone.sync . 144iii

BackboneJSBackboneJS-Sync Backbone.emulateHTTP . 146BackboneJS-Sync Backbone.emulateJSON . 14810. BackboneJS – View . 150BackboneJS – View Extend . 151BackboneJS – View Initialize . 152BackboneJS – View El . 154BackboneJS – View el . 155BackboneJS – View setElement . 157BackboneJS – View Attributes . 159BackboneJS – View (jQuery) . 161BackboneJS – View Template . 163BackboneJS – View Render . 165BackboneJS – View Remove . 167BackboneJS – View delegateEvents . 169BackboneJS – View undelegateEvents . 17111. BackboneJS – Utility . 173BackboneJS-Utility Backbone.noConflict . 173BackboneJS-Utility Backbone. . 175iv

1. BackboneJS – OverviewBackboneJSBackboneJS is a lightweight JavaScript library that allows to develop and structure theclient side applications that run in a web browser. It offers MVC framework which abstractsdata into models, DOM into views and bind these two using events.History: BackboneJS was developed by Jeremy Ashkenas and was initially releasedon October 13th, 2010.When to use Backbone Consider you are creating an application with numerous lines of code using JavaScriptor jQuery. In this application, if you:oadd or replace DOM elements to the application oromake some requests oroshow animation in the application oroadd more number of lines to your code,then your application might become complicated. If you want a better design with less code, then it is better to use the BackboneJSlibrary that provides good functionality, is well organized and in a structured mannerfor developing your application. BackboneJS communicates via events; this ensures that you do not mess up theapplication. Your code will be cleaner, nicer and easy to maintain.FeaturesThe following are a list of features of BackboneJS: BackboneJS allows developing of applications and the frontend in a much easier wayby using JavaScript functions. BackboneJS provides various building blocks such as models, views, events, routersand collections for assembling the client side web applications. When a model changes, it automatically updates the HTML of your application. BackboneJS is a simple library that helps in separating business and user interfacelogic. It is free and open source library and contains over 100 available extensions. It acts like a backbone for your project and helps to organize your code.5

BackboneJS It manages the data model which includes the user data and displays that data at theserver side with the same format written at the client side. BackboneJS has awith Underscore.js. It allows to create client side web applications or mobile applications in a wellstructured and an organized format.softdependencywith jQuery andaharddependency6

2. BackboneJS – Environment SetupBackboneJSBackboneJS is very easy to setup and work. This chapter will discuss the download and setupof the BackboneJS Library.BackboneJS can be used in the following two ways: Downloading UI library from its official website. Downloading UI library from CDNsDownloading the UI library from its official websiteWhen you open the link http://backbonejs.org/, you will get to see a screenshot as shownbelow:As you can see, there are three options for download of this library: Development Version - Right click on this button and save as and you get the fullsource JavaScript library. Production Version - Right click on this button and save as and you get theBackbone-min.js library file which is packed and gzipped. Edge Version - Right click on this button and save as and you get an unreleasedversion, i.e., development is going on; hence you need to use it at your own risk.DependenciesBackboneJS depends on the following JavaScript files:7

BackboneJS Underscore.js: This is the only hard dependency which needs to be included. You canget it from here. jQuery.js: Include this file for RESTful persistence, history support viaBackbone.Router and DOM manipulation with Backbone.View. You can get itfrom here. json2.js: Include this file for older Internet Explorer support. You can get it from here.Download UI Library from CDNsA CDN or Content Delivery Network is a network of servers designed to serve files to users.If you use a CDN link in your web page, it moves the responsibility of hosting files from yourown servers to a series of external ones. This also offers an advantage that if the visitor toyour webpage has already downloaded a copy of BackboneJS from the same CDN, it won'thave to be re-downloaded.As said above, BackboneJS has a dependency of the following JavaScript: jQuery UnderscoreHence CDN for all the above is as follows: script type "text/javascript"src 2/jquery.min.js" /script script type "text/javascript"src 1.4/underscoremin.js" /script script type "text/javascript"src 3/backbonemin.js" /script Note: We are using the CDN versions of the library throughout this tutorial.ExampleLet's create a simple example using BackboneJS. !DOCTYPE html html head meta charset "UTF-8" meta http-equiv "X-UA-Compatible" content "IE edge,chrome 1" title Hello World using Backbone.js /title 8

BackboneJS /head body !-- -- !-- Your HTML -- !-- -- div id "container" Loading. /div !-- -- !-- Libraries -- !-- -- script src "https://code.jquery.com/jquery-2.1.3.min.js"type "text/javascript" /script scriptsrc .js/1.3.3/underscoremin.js" type "text/javascript" /script script src s/0.9.2/backbonemin.js" type "text/javascript" /script !-- -- !-- Javascript code -- !-- -- script type "text/javascript" var AppView Backbone.View.extend({// el - stands for element. Every view has an element associated with HTMLcontent, will be rendered.el: '#container',// It's the first function called when this view is instantiated.initialize: function(){this.render();},// el - it's a cached jQuery object (el), in which you can use jQueryfunctions to push content. Like the Hello TutorialsPoint in this case.9

BackboneJSrender: function(){this. el.html("Hello TutorialsPoint!!!");}});var appView new AppView(); /script /body /html The code comments are self-explanatory. A few more details are given below:There's a html code at the start of body tag div id "container" Loading. /div This prints Loading.Next, we have added the following CDNs script src "https://code.jquery.com/jquery-2.1.3.min.js"type "text/javascript" /script scriptsrc .js/1.3.3/underscoremin.js" type "text/javascript" /script script src s/0.9.2/backbonemin.js" type "text/javascript" /script Next, we have the following script:var AppView Backbone.View.extend({// el - stands for element. Every view has an element associated with HTMLcontent, will be rendered.el: '#container',// It's the first function called when this view is instantiated.initialize: function(){this.render();},// el - it's a cached jQuery object (el), in which you can use jQueryfunctions to push content. Like the Hello World in this case.10

BackboneJSrender: function(){this. el.html(" h1 Hello TutorialsPoint!!! /h1 ");}});var appView new AppView();The comments are self-explanatory. In the last line, we are initializing new AppView(). Thiswill print the "Hello TutorialsPoint" in the div with id "container"Save this page as myFirstExample.html. Open this in your browser and the screen will showthe following text.11

3. BackboneJS – ApplicationsBackboneJSThe BackboneJS gives a structure to the web applications that allows to separate businesslogic and user interface logic. In this chapter, we are going to discuss the architectural styleof the BackboneJS application for implementing user interfaces. The following diagram showsthe architecture of BackboneJS :The architecture of BackboneJS contains the following modules: HTTP Request Router View Events12

BackboneJS Model Collection Data SourceLet us now discuss all the modules in detail.HTTP RequestThe HTTP client sends a HTTP request to a server in the form of a request message whereweb browsers, search engines, etc., acts like HTTP clients. The user requests for a file suchas documents, images, etc., using the HTTP request protocol. In the above diagram, youcould see that the HTTP client uses the router to send the client request.RouterIt is used for routing the client side applications and connects them to actions and eventsusing URL's. It is a URL representation of the application's objects. This URL is changedmanually by the user. The URL is used by the backbone so that it can understand whatapplication state to be sent or present to the user.The router is a mechanism which can copy the URL's to reach the view. The Router is requiredwhen web applications provide linkable, bookmarkable, and shareable URL's for importantlocations in the app.In the above architecture, the router sending an HTTP request to the View. It is a usefulfeature when an application needs routing capability.ViewBackboneJS views are responsible for how and what to display from our application and theydon't contain HTML markup for the application. It specifies an idea behind the presentation ofthe model's data to the user. Views are used to reflect "how your data model looks like".The view classes do not know anything about the HTML and CSS and each view can be updatedindependently when the model changes without reloading the whole page. It represents thelogical chunk of the UI in the DOM.As shown in the above architecture, the View represents the user interface which isresponsible for displaying the response for the user request done by using the Router.EventsEvents are the main parts of any application. It binds the user's custom events to anapplication. They can be mixed into any object and are capable of binding and triggeringcustom events. You can bind the custom events by using the desired name of your choice.Typically, events are handled synchronously with their program flow. In the abovearchitecture, you could see when an event occurs, it represents the model's data by usingthe View.13

BackboneJSModelIt is the heart of the JavaScript application that retrieves and populates the data. Modelscontain data of an application, logic of the data and represents the basic data object in theframework.Models represents business entities with some business logic and business validations. Theyare mainly used for data storage and business logic. Models can be retrieved from and savedto data storage. A Model takes the HTTP request from the Events passed by the View usingthe Router and synchronizes the data from the database and sends the response back to theclient.CollectionA Collection is a set of models which binds events, when the model has been modified in thecollection. The collection contains a list of models that can be processed in the loop andsupports sorting and filtering. When creating a collection, we can define what type of modelthat collection is going to have along with the instance of properties. Any event triggered ona model will also trigger on the collection in the model.It also takes the request from the view, bind events and synchronizes the data with therequested data and sends the response back to the HTTP client.Data SourceIt is the connection set up to a database from a server and contains the information which isrequested from the client. The flow of the BackboneJS architecture can be described as shownin the following steps: A User requests for the data using the router, which routes the applications tothe events using the URL's. The view represents the model's data to the user. The model and collection retrieves and populates the data from the database bybinding custom events.In the next chapter, we will understand the significance of Events in BackboneJS.14

BackboneJSEnd of ebook previewIf you liked what you saw Buy it from our store @ https://store.tutorialspoint.com15

Underscore.js: This is the only hard dependency which needs to be included. You can get it from here. jQuery.js: Include this file for RESTful persistence, history support via Backbone.Router and DOM manipulation with Backbone.View. You can get it from here. json2.js: Include this file for older Internet Explorer support. You can get it from here.

Related Documents:

tutorialspoint.com or google.com these are domain names. A domain name has two parts, TLD (Top Level Domain) and SLD (Second level domain), for example in tutorialspoint.com, tutorialspoint is second level domain of TLD .com, or you can say it's a subdomain of .com TLD. There are many top level domains available, like .com,

tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the

tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the

tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the

tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the

tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the

All the content and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws.

A programming manual is also available for each Arm Cortex version and can be used for MPU (memory protection unit) description: STM32 Cortex -M33 MCUs programming manual (PM0264) STM32F7 Series and STM32H7 Series Cortex -M7 processor programming manual (PM0253) STM32 Cortex -M4 MCUs and MPUs programming manual (PM0214)