Writing HTML5 Mobile Web Apps using Backbone.js
Upcoming SlideShare
Loading in...5
×
 

Writing HTML5 Mobile Web Apps using Backbone.js

on

  • 36,983 views

A full HTML5 mobile development stack, including PhoneGap, trigger.io, Backbone.js, Require.js, jQuery Mobile, Sencha Touch, jqMobi, and Mustache. The lecture provides best practices towards ...

A full HTML5 mobile development stack, including PhoneGap, trigger.io, Backbone.js, Require.js, jQuery Mobile, Sencha Touch, jqMobi, and Mustache. The lecture provides best practices towards developing a mobile application using HTML5 and Javascript.

Statistics

Views

Total Views
36,983
Views on SlideShare
35,096
Embed Views
1,887

Actions

Likes
92
Downloads
726
Comments
3

19 Embeds 1,887

http://www.scoop.it 935
http://vietgamedev.net 771
http://eduardojoaquimsilva.wordpress.com 121
https://twitter.com 28
http://ervdesign.lan 5
https://twimg0-a.akamaihd.net 4
http://ervdesign.net 4
https://eduardojoaquimsilva.wordpress.com 3
http://translate.googleusercontent.com 3
http://us-w1.rockmelt.com 3
http://www.slashdocs.com 2
http://www.pearltrees.com 1
http://workality-ervdesign.lan 1
http://www.techgig.com 1
https://duckduckgo.com 1
http://www.twylah.com 1
http://tweetedtimes.com 1
http://a0.twimg.com 1
http://www.m.techgig.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Writing HTML5 Mobile Web Apps using Backbone.js Writing HTML5 Mobile Web Apps using Backbone.js Presentation Transcript

  • Writing HTML5 Mobile Web Apps A complete development stack Ron Reiter (Any.DO)
  • AgendaHTML5 or native?HTML5 Mobile Development Frameworks PhoneGap Trigger.IOUI Frameworks jQuery Mobile Sencha Touch jqMobiMVC with Backbone.jsClient Side Templating with MustacheModular Javascript with RequireJS
  • Go web or native?Web NativeCross-platform code. Smoother user interface.CSS3 is very powerful, easy and More control and flexibility (forflexible compared to Android and example, PhoneGap does notiPhone UI libraries. export all native abilities).Easy to patch / update because only You will need to write Javascript toweb assets need to be replaced. native interfaces if your back-end / business logic is already programmed using native codeAll you need to know is Javascriptfor all platforms.Static elements and transitions arestill laggy.
  • My suggestionUse WebViews when you need to have a complicated,good looking user interface, and if you need it fastUser native UI when you need very CPU intensive, sleekinterface, and you are willing to invest a lot of work on itUse a combination of both to gain both advantages! Usenative static elements (header, footer, page frames andpage transitions), and program the actual user interface inWebViews
  • Mobile Development Frameworks PhoneGap, Trigger.IO
  • PhoneGapCross platform open source framework for writing mobileappsWrite your program once, and compile an app for Android,iPhone, BlackBerry, Windows Phone, and more…Exports Javascript APIs for native phone control (camera,GPS, filesystem, etc.) and has plugins
  • PhoneGap APIsAccelerometer EventsCamera FileCapture GeolocationCompass MediaConnection NotificationContacts StorageDevice
  • Trigger.IOSimilar to PhoneGap, but commercialHas a utility called forge which does the app building foryou, instead of opening 3 completely different IDEs to do ityourselfClaims to outperform PhoneGap native bridge by x5You should choose it if you can write your program inJavascript only (no plugins)Good for web, too!
  • Trigger.IO
  • UI FrameworksjQuery Mobile, Sencha Touch, jqMobi
  • UI FrameworksIf you decide to build all of your mobile UI using a webframework, you should use a UI framework which saves timewith mobile-looking componentsjQuery Mobile – Free, heavily backed by the community http://jquerymobile.com/Sencha Touch – Commercial, robust http://www.sencha.com/products/touchjqMobi – Haven‟t tried it, but it looks promising in terms ofperformance, which is the Achilles heel of mobile web UI http://www.jqmobi.com/ http://www.youtube.com/watch?v=MwNdWZsRXgk
  • The Fixed Toolbar NightmareEither you have a new device which supports real fixedtoolbars, or you simulate the scrolljQuery goes with real toolbars & fallback support.Fallbacks to statically positioned toolbarsSencha Touch goes for compatibility and simulates thescroll by moving the body up instead of letting the pagescroll downIf you really want both performance and compatibility - thebest solution would probably be… to use native toolbars
  • jQuery MobilejQuery Mobile does not use jQuery – you can usewhatever you want for DOM manipulationEvolved a lot in the past year and is ready for real worlddevelopmentAlthough performance has improved a lot, it‟s still notamazing. You might want to do a little more research
  • jQuery Mobile FeaturesPages and sliding page transitions, toolbars (header,footer, fixed), navigation pane, forms, themes and more
  • Codiqa – Rapid jQuery Mobile Prototyping
  • MVC Frameworks
  • ComparisonBackbone.js, Spine.js – very similar librariesEmber.js – has automatic updating templates, which arevoodooish, and bindings work a bit differentEmber should be nicer to program with, but Backbonegives more control and performance
  • Backbone.js
  • Backbone.jsBackbone.js is a minimal, popular, generic MVCframework for writing heavy HTML5 web & mobileapplicationsWho uses Backbone.js? LinedIn, Soundcloud, Basecamp, Codiqa, and more
  • Backbone.jsBackbone.js makes you program user interface the rightwayAn object model with inheritanceREST SyncCan be used with jQuery/Zepto, MooTools, etc. for DOMmanipulation
  • Code with BackboneCode without Backbone Code with Backbonefunction createListView(id) { Var ListView = Backbone.View.extend({ tagName: “div”, var listView = $(“<div>”).addClass(“list”) className: “list”, .click(function(e) { events: { if ($(e).is(“li”)) “click li” : “clickItem”, $(e.target).addClass(“selected”); “keypress” : “deleteOnKeypress” $(this).data(“selected”, $(e.target) }, .text()); clickItem: function(e) {}).keypress(function(e) { $(e.target).addClass(“selected”); if (e.keyCode == 8) { this.selected = $(e.target).text(); $(this).find(“.selected”).remove(); }, }); deleteOnKeypress: function(e) { if (e.keyCode == 8) { return listView; $(this.el).find(“.selected”).remove();} } }var listView = createListView(); } var listView = new ListView();
  • Quick REST TutorialREST = REpresentational State TransferIt is a protocol which servers implement to give control ofthe state of a data set (a collection of data items)REST maps CRUD operations to HTTP operations Collection Operations HTTP GET = Read HTTP POST = Create Model Operations HTTP PUT = Update HTTP DELETE = Delete
  • Backbone MVC Architecture Server Model Database Backbone REST Sync Model View Backbone.Model HTML + CSS Model updated DOM Manipulation according to With jQuery and user interaction templating Controller Backbone.View DOM View EventsModel Events
  • Backbone ModelThe Backbone.js Model represents a single data entityIt is usually bound to a view in such a way that every timeit changes, the view is updated accordingly (MVC) change/delete Model View
  • Backbone.js ModelBackbone fires “change” and “destroy” events whenspecific models are updated or deleted.Without regarding views, Backbone also automaticallysynchronizes models back to the server on every change Model Server
  • Backbone Model task.save({ title: “Get Rich”, done: false }); change:title Model ViewHTTP PUT /tasks/1 Server
  • Backbone Model task.destroy() destroy Model ViewHTTP DELETE /tasks/1 remove Server
  • Backbone CollectionA Backbone Collection object stores a set of models of thesame typeIt configures the REST endpoint in the server for the dataset Model Model Collection Server Model
  • Backbone CollectionBackbone collections can fetch a collection from theserverA “reset” event is fired when results from the server return tasks.fetch(); tasks.bind(“reset”, this.addTaskViews); HTTP GET /tasks Collection Server Model Model Model
  • Backbone CollectionBackbone collections have the “create” method, whichcreates a new model tasks.create({ title: “Hello, world!”, done: false }); tasks.bind(“add”, this.addTaskView) New Model New Model Model HTTP POST /tasks Model Collection Server New task ID: 3 Model
  • Summary - Backbone REST Architecture Model OperationsCollection Operations Collection GET /tasks PUT /tasks/38 POST /tasks View Model DELETE /tasks/38 PUT /tasks/39 View Model DELETE /tasks/39 PUT /tasks/40 View Model DELETE /tasks/40 PUT /tasks/41 View Model DELETE /tasks/41
  • Backbone ViewViews represent a model or a collection of models, andare responsible for managing their child viewsBackbone creates a DOM element with a specific class forevery new view, using the tagName and className tagsOr, Backbone can use a view which already exists in theDOM, if el is defined Backbone.View.extend({ Backbone.View.extend({ tagName : “div”, el: $(“#main-view”); className: “section” }) }) … <div id=“main-view”></div>
  • Backbone ViewThe View is the most important class of Backbone, sinceit‟s actually an MVC controller. (Bad choice of words.Check out spine.js for a better choice)It translates the user actions into model changesIt updates the view when a model is changed
  • Backbone ViewLet‟s create a todo item view, which represents a singletodo item in a todo list var todoItemView = Backbone.View.extend({ tagName: “div”, className: “todo” }); View
  • Backbone ViewNow let‟s add the model it is bound to var todoItemView = Backbone.View.extend({ tagName: “div”, className: “todo”, model: todoModel }); Model View
  • Backbone ViewGet notified when the model is changed by binding onmodel change events, so we‟ll know we need to update it var todoItemView = Backbone.View.extend({ tagName: “div”, className: “todo”, model: todoModel, initialize: function() { Model _.bindAll(this, “update”); this.model.bind(“change”, this.update); } }); View
  • Backbone ViewWhen checking off the task, we want to know about it. Solet‟s add a checkbox change handler var todoItemView = Backbone.View.extend({ tagName: “div”, className: “todo”, model: todoModel, initialize: function() { Model _.bindAll(this, “update”, “check”); this.model.bind(“change”, this.update); }, events: { “change .done-checkbox” : this.check } }); View X
  • Backbone ViewNow, let‟s toggle the task‟s “done” status in the function“check” var todoItemView = Backbone.View.extend({ tagName: “div”, className: “todo”, model: todoModel, initialize: function() { Model _.bindAll(this, “update”, “check”); this.model.bind(“change”, this.update); }, events: { “change .done-checkbox” : this.check }, check: function() { this.model.save({ done: !this.model.get(“done”); }); } View }); X
  • Backbone ViewLet‟s update the view when we receive the “update” event var todoItemView = Backbone.View.extend({ tagName: “div”, className: “todo”, model: todoModel, initialize: function() { _.bindAll(this, “update”, “check”); this.model.bind(“change”, this.update); Model }, events: { “change .done-checkbox” : this.check }, check: function() { this.model.save({ done: !this.model.get(“done”); }); X }, update: function() { this.title.text(this.model.get(“title”)); if (this.checkbox.val()) { View $(this.el).addClass(“checked”); } else { $(this.el).removeClass(“checked”); }} });
  • Rendering a ViewWhen creating a new view, you must implement and callits render function to build its inner elementsYou can implement the render function in 3 ways1. Don‟t implement it – if you are using an existing element2. Use jQuery or another DOM library to build the inner elements using code – results in ugly and unreadable code3. Use a template to render the view – preferred method
  • {{ Mustache }} TemplatingMustache is a common logic-less templating librarySupports a wide range of languagesSimple syntax, yet powerfulSupports loopsYou can use underscore.js templates, but they are not asstrong
  • Rendering using Mustache Let‟s use jQuery‟s .html() function to fill our element with the rendered template Use Mustache.render with the view template text , along with the models‟ data (we use toJSON to serialize the model data so the template engine can use it). Templat ModelBackbone.View.extend({ e render: function() { $(this.el).html( Mustache.render(todoItemTemplate, Mustache this.model.toJSON())); }); View
  • Updating a View When updating a view, you may use two methods:1. If you are using a template, you may use the render function with the updated attributes again2. Acquire handles to the DOM elements you created in the render function and update each of them according to the change. The first method is a lot easier to implement, but when you need performance, you should later on move to option #2.
  • Optimistic ModeOptimistic mode (Default) Creates/updates views before confirmation from server Gives better user experienceWait mode Creates/updates views after confirmation from server Safer methodIf you have business logic related to how your entities arecreated which implicates on the views, you cannot useoptimistic mode
  • RequireJS
  • RequireJSModular Javascript libraryImportant when writing big projectsLoads modules asynchronously – allows the page to loadefficientlyAllows minification of the whole project into one file
  • How to use RequireJSBoilerplate code example https://github.com/ronreiter/webapp-boilerplateRequireJS loads “AMD” modules (Asynchronous ModuleDefinition” as opposed to the company )Normal modules add a global variable (jQuery adds $ forexample), or add method over a global variable (like jQueryplugins).This means that you CANNOT use normal libraries, withoutwrapping them first.I„ve wrapped them for you, so just download my boilerplate anduse it.
  • Code with RequireJSCode without Require.JS Code with Require.JS<script src=“foo1.js”></script> <script src=“require.js”></script><script src=“foo2.js”></script> <script><script src=“foo3.js”></script> require([“foo1”, “foo2”, “foo3”, “foo4”],<script src=“foo4.js”></script> function(foo1, foo2, foo3, foo4) {<script> foo1.do(); foo1.do(); foo2.do(); foo2.do(); foo3.do(); foo3.do(); foo4.do(); foo4.do(); });</script> </script>foo4.js: foo4.js:// hmmm. Can I use foo1, foo2, and foo3? define([“foo1”, “foo2”, “foo3”],// let‟s put foo4 as a global variable. function(foo1, foo2, foo3) {window.foo4 = … var foo4 = … return foo4; });
  • RequireJS + Templating Another awesome advantage of RequireJS is that it knows how to load text files along with the modules, so you can simply write your client side template files separately, and load them when you need themdefine([“backbone”, “underscore”, “jquery”, “text!listview.html”], function(Backbone, _, $, listViewTemplate) {… Mustache.render(listViewTemplate, this.model.toJSON()) …
  • OptimizationOnce you finish writing your project, simply run a utilitycalled r.js (part of RequireJS) on your main scriptr.js is a node executable scriptIt will turn all of your modules into one single, minified fileCreating an application manifest is required node r.js JS JS min JS JS JS
  • Thank You!Questions?