• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Viking academy  backbone.js
 

Viking academy backbone.js

on

  • 684 views

Introduction to backbone.js

Introduction to backbone.js

Statistics

Views

Total Views
684
Views on SlideShare
684
Embed Views
0

Actions

Likes
4
Downloads
11
Comments
1

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

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

11 of 1 previous next

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

    Viking academy  backbone.js Viking academy backbone.js Presentation Transcript

    • backbone.js and single-page web apps http://backbonejs.org/Bert Wijnants - Mobile Vikings - 9 november 2012
    • Lets start with a little historyJavascript was invented by Netscape in 1995,and the web looked like...
    • iteractive website:<marquee>, <blink>
    • the rise of AJAX (2004)gmail is the first single-page web app
    • more and more javascripta website is:lots of html pages with some javascriptajax returns htmla webapp is:lots of javascript with some html pagesajax returns jsonfront-end is taking over program logicnecessary to create highly responsive user interfaces
    • #7 6 in top 7 on Github is javascript
    • Why another framework? weve got jQuery, right?
    • Whats wrong with jQuery?jQuery is very useful for DOM manipulations,events, ajax,... (cross-browser)and btw: use zepto.js for mobile devices (webkit only)DOM manipulation = very expensive taskbreaks hardware accelerationalways avoid unnecessary DOM manipulationsespecially on mobile devicesToo easy to use the DOM for state of your app
    • How to avoid DOM manipulations? important rule The DOM is write-only! dont use it to store the state of your app its for presentation purposes only
    • Bad:$(".button").click( function(event) { if (!$(this).hasClass("selected")) { $(this).parent().find(".button.selected").removeClass("selected); $(this).addClass("selected") }});Dont read from the DOM to know which of the buttons isselected
    • But where to store everythingif DOM is not allowed?Here backbone.js kicks in...
    • backbone.jsevery good framework has "a sentence" :-)Backbone.js gives structure to web applications byproviding models with key-value binding and custom events, collections with arich API of enumerable functions, views with declarative event handling, andconnects it all to your existing API over a RESTful JSON interface.Single-page web apps with hundreds of lines of javascript.Most apps just give structure with namespaces:var namespace = (function() { return { .... }})(); We need more structure than this!
    • backbone.jsPretty maturestarted 2 years agopopular on githubversion 0.9.2, 1.0 coming upfrom the creators of underscore.js and coffeescriptLightweightjust 2 dependencies: underscore, jquery/zeptoAlso runs on node.jsSame models in front-end and back-end
    • Annotated source
    • MVC framework or whateverits not really MVC, its MVVM!ModelViewViewModel (=DOM)where is the controller?skinny controller, fat modelprogram logic in models and views
    • DOM Model MODEL html javascript is the only source of truth! is pure javascript Models and Collections Collection is an array of Models
    • EventsLots of events are firedwith these naming conventions:"add" (model, collection) — when a model is added to a collection."remove" (model, collection) — when a model is removed from a collection."reset" (collection) — when the collections entire contents have been replaced."change" (model, options) — when a models attributes have changed."change:[attribute]" (model, value, options) — when a specific attribute has been updated."destroy" (model, collection) — when a model is destroyed."sync" (model, collection) — triggers whenever a model has been successfully synced to the server."error" (model, collection) — when a models validation fails, or a save call fails on the server."route:[name]" (router) — when one of a routers routes has matched."all" — this special event fires for any triggered event, passing the event name as first argument.
    • render change eventsDOM View Model html events change data VIEW observes model changes html javascript is pure javascript render function to write to DOM this.el is the element in DOM observes events from DOM (click, touchmove, ...)
    • Model-backed viewsvar model = new Todo({ title: foo, done: false});var view = new TodoView(model);View has direct access to model.Model does not. View listens to change events.
    • Persistency a.k.a the databasejavascript applications usually work like this:get_all()get_one()save_one()update_one()delete_one()and the same on server-side: CRUDLots of code for repetitive operations
    • SyncBackbone.js has a sync moduleCRUD interfaceGET /modelGET /model/<id>POST /modelUPDATE /model/idDELETE /model/idcan be overwritten granularly. examples:use localstorage for all fetch operationsuse sockets instead of REST over http
    • render change eventsDOM View Model html events change data sync web service html javascript SYNC asynchronous persistency
    • Model.syncIn a Model or Collection:fetch()save()remove()dont care about whats going on in the back
    • More stuff:Model validation on client-sideyou can only save() a valid modelRoutereasy url handling (with # or #!)works with History API, so back button worksUnderscore functionsmap, reduce, for each, client-side templates, ...
    • example: Modelvar Todo = Backbone.Model.extend({ defaults: { "title" : "(empty)", "done" : false }, toggle: function() { this.set({ "done" : !this.get("done") }); this.save(); }, clear: function() { this.destroy(); }});
    • example: Collectionvar TodoList = Backbone.Collection.extend({ model: Todo, initialize: function() { this.fetch(); }, done: function() { return this.filter(function(todo){ return todo.get(done); }); }, remaining: function() { return this.without.apply(this, this.done()); },});
    • example: Viewvar TodoView = Backbone.View.extend({ tagName: "li", template: Templates.todo, initialize: function() { this.model.bind(change, this.render, this); this.model.bind(destroy, this.remove, this); }, render: function() { this.$el.html(this.template(this.model.toJSON())); this.$el.toggleClass(done, this.model.get(done)); return this; }});
    • example: View (continued)events: { "click .toggle" : "toggleDone", "click .clear" : "clear"},toggleDone: function() { this.model.toggle();},clear: function() { this.model.clear();}
    • ProblemsSyntax is not very clearLots of ( { "=> coffeescript can help with thisThe use of thisyou loose scope quite easily in javascript=> var self = this to the rescueSteep learning curvebut documentation is very goodlots of support on stackoverflow
    • Advantagesstructured javascriptwrite-only DOMdesigned for web appssyncing with back-end = trivialnaming conventions (events, render, ...)model change => view rendervery popular: big community
    • Getting startedhttp://backbonejs.orgEverything you need is hereOr check out the webapp for VikingSpots NG:github.com/deals-platform/mobile-apps/html5 Questions? Remarks?