Backbone js-slides


Published on

Published in: Technology, Business
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Dear ladies and gentlemen. Welcome on the Backbone.js session.
  • My name is Vadim and I am a lead developer in Trellon. Currently I am writing Backbone.js CooBook for the PACKT Publishing. I am completing finale chapters and I hope it will be punished very soon. If you want to have a discount, please, contact me via email or twitter so I can provide you voucher.
  • Do you remember those lovely days when everybody was using DHTML pages with some JavaScript inside? For example there were so many scripts that checked if the form was correctly filled and showed dialog boxes if it is not.
  • Just remind how fun it was in 1995! Actually I started to use Internet in 1999, when I was still in school. There was no so many JavaScript powered web pages, but it was very cool to see snowflakes floating on the screen on the Merry Christmas eve! This is how JS was used at this time.
  • And then in 2000 Microsoft invented XMLHttpRequest. 5 years (!) had been passed since we called it AJAX. Incredible, but in 1998 people were using iframes to do the same!
  • In 2006 we first saw jQuery. It was awesome! It allowed do so many new things: * Use CSS selectors for DOM traversing * Do vent handling * Perform AJAX * Make animation * Achieve compatibility with old browsers It was amazing! BTW is is going to be jQuery conference in Portland soon: on June 13 & 14 this year.
  • And what we are working with in the 2013? There are so many new things that have appeared during recent years. Now it is time remind them.
  • Alright! * Now we have HTML5 that provides so many cool things. * Fore example in HTML5 there is Local Storage and if is used, your application can keep data in the browser storage when there is no Internet connection, and synchronize data with a remote server when connection is available. * Push state allows to update URL in the browser without need to reload the page.. Remember that before we used # in the URL to be able to change. And now not, this gives us some possibilities to create Search Engines compatible dynamic web apps. * Now we also have JS templating engines on the client-side that allows to unload the server and to transfer JSON instead of HTML code. * We also have REST (Representational State Transfer), which is an architectural style which implies that server deals with data, while client is involved into interaction with a user. With REST we can easily replace the server or the client with alternative server or a cleint.
  • And what about JS evolution seen last years.
  • First, clients is eacoming more complex be able to do much more things then ever before.
  • Second, they became more thick, may contain some business logic and, obviously, perform rendering. Server just stores data and checks access permissions. Also just want to note, that we are seeing this thin-to-thick clients transition once again. TODO: In Unix time there was X Windows System that allowed user to access server resources, and client was very thin.
  • And third, browsers executes JavaScript 10 times faster then it was 10 years ago. JS client applications works really fast now! And even performance on mobile devices is not bad.
  • But we still have some problems!
  • Right now typical AJAX code looks like this. And there is something wrong about it! Here we do: a) Event handling b) AJAX request c) Data rendering d) DOM updates That's to much for the single piece of code! This code looks the same as it was when developers where creating first desktop programs at the dawn of programming. Or the same as website development when there was no many MVC frameworks for the web.
  • Also, AJAX in Drupal. Have you ever deal with any JavaScript when building AJAX application with Drupal? There is cool form API, AHAH, we are defining AJAX settings in PHP arrays.
  • D'oh!
  • Let's do things properly! Can we? I mean use just JavaScript when it is intended to be used, and use proper MVC framework so there is no mess in the code. Yeah, there is a way!
  • Meet! ... Backbone... JS!
  • Whoohoo!
  • Backbone.js was created by Jeremy Ashkenas, author of the CoffeScript in 2010. Backbone.js is based on the Undersore.js library which provides many useful functions to work with arrays, collections, objects, events, and so on. Backbone.js requires jQuery or Zepto Zepto is 99% compatible with jQuety, which is smaller and faster but works only in modern browsers.
  • Let's speak about Backbone.js advantages. * It is minimalistic and easy integrates with other frameworks. * It is modular, which means you can use only required functionality. * It also has perfect OOP design and can be easily extended and overridden * Also there is a growing amount of Backbone.js extension. And now it is more then 100. * And there is a nice community. 90% of my issues I created on GitHub received feedback. This is really great. Community grows the day after the day. And I like it.
  • There are many similar frameworks, why we are speaking about Backbone.js now?
  • Because you should now how new frameworks appears. Look at this slide!
  • And finally Backbone.js was chosen by many world knows startups and websites. * Groupon Now!'s team decided their first product to be AJAX heavy, but still linkable and shareable. Despite they were completely new in Backbone, they found it's learning curve was incredible quick, so they were able to deliver the working product just in two weeks. * Foursquare used Backbone.js library to create model classes for the entities in foursquare (e.g. venues, checkins, users). They found that Backbone’s model classes provide a simple and lightweight mechanism to capture object data and state, complete with the semantics of classical inheritance. * LinkedIn Mobile used Backbone.js to create it's ts next-generation HTML5 mobile web app. Backbone made it easy to keep the app modular, organized and extensible so that it was possible to program the complexities of LinkedIn's user experience. * Airbnb is a community marketplace for users to list, discover, and book unique spaces around the world. Development team uses Backbone in many latest products. Recently they rebuilt mobile website with Backbone.js and Node.js tied together with a library they're calling Rendr.
  • Let's learn how to create backbone applications.
  • Backbone.js operates with following objects * Model contains data and provides business logic used in the application. * Collection is a set of models that can be processed in the loop and supports sorting and filtering. * View renders model or collection and interacts with the user. * Templates are used for separation HTML from JavaSript in the View. By default Undescore template engine is used, but it can be replaced with Twig, which is used in Drupal 8 or Mustache. * Router is similar to hook_menu. It allows to define a path and provide callbacks. * History is global object, which contains router that is currently in use. * Backbone objects such as Models, Collections, Views and Router implements Events object, they can provide own events and listen to events from other objects.
  • There are some differences in Backbone architecture and traditional MVC pattern. At the left there is a MVC structure . Here we see, that the Model updates the View seen by the user. User can perform actions which are handled by the Controller. Controller manipulates model data and can trigger business logic methods. Also Models is synchronized with a storage. At the right you can see Backbone.js structure. The main difference is that some of the controller functionality is implemented by the View, while other by the router. Typically view can listen model events and update DOM. View also listens to user events and updates model accordingly. Model is synchronized with a server using REST approach. Read ops are typically controlled by the Router, while write ops by the View.
  • Let's make some demo!
  • Let's start with some easy example. Here we just render the collection of models with Backbone.js.
  • Now we can move forward and learn how to add some cool features into our application.
  • Here is how we can use REST with our models and collections.
  • Here is how we can use REST with our models and collections.
  • Here is how we can use REST with our models and collections.
  • Here is how we can use REST with our models and collections.
  • Here is how we can use REST with our models and collections.
  • Some other cool things you will find in Backbone.js CookBook. I am working on final chapters and soon the book will be published. Contact me or leave your business card please, so I can provide you with a discount voucher.
  • Ok, now let's understand how Backbone deals with Drupal.
  • To pass data from Drupal to Backbone.js we can use following methods. Bootstrapping. This is the technique we saw above: we can create model and collection objects and populate them with data directly in JS code. In D7 we can pass data as settings into JS code. (TODO: add example). REST (Representational State Transfer) – is an architectural style for designing network applications which communicate between each other using HTTP protocol and passing data in JSON format or any other appropriate HTTP data type. In this case Backbone.js client and Drupal synchronizes data via REST. In Drupal 7 RESTful service can be implemented using Services / RESTful web-services modules. Backbone module provides more convenient way for Backbone client to communicate with Drupal. It is also based on the REST approach. Let's see how those approaches works in detail.
  • Let's understand how REST works. REST-style architectures consists of clients and servers. Client calls HTTP request method (POST, GET, PUT, DELETE) to perform CRUD (created, read, update, delete) operation over a resource, which can be either a collection or a single element. There can be a resource that represents multiple or single object. Depending on the request and resource type one or another operation can be performed. Following table shows it.
  • Here is how we can use REST with our models and collections.
  • Here is how we can use REST or our models and collections.
  • Here is one more way of dealing with Backbone.js in Drupal. There is Drupal module called Backbone that can provide node, comment and user entities on the client side where Backbone is running. It works via REST and integrates with both Services and RESTful web services modules. It also provides lists of users and nodes and even content of Drupal view to the Backbone app! This module just saves much time.
  • Let's see how it works. As we said before Backbone is pretty extensible, so we extend default models and collections. This example shows how we can get Drupal entities from the View and work with them as with Backbone Collection. We simply need to know view name and nothing else to get those entities. That's really cool! Thanks to ****, author of this module.
  • This module is still in development, which means that there will be many new features. Such as bootstrapping support, better views support. It will allow to do in-place content editing, drag and drop support to reorder things. And may be we will see D8 version.
  • Guess how Bakcbone.js is related to Drupal8?
  • It's in core! Along with other libraries such as jQuery or jQuery UI! It is event in D8 Wow! Some of the existing functionality is completely being rebuilt using Backbone.js: in-place editing, layouts, toolbar and many other. You can refer to the following links to understand what's going on in D8. You can also take part in the Drupal Code sprint at Friday.
  • One more thing we need to talk about. Drupal 8 is now much powerful then it was. It is based on Symphony and uses much more OOP then ever before. There can be controller class for operating with entities, configuration, permissions and other data stored in the system. Now logic is completely separated from the representation. And it is quite easy module to define REST resources to access it's data. So REST support is in core and will basically provided by any Drupal 8 module. Also Twig is in core too. Twig is a templating engine that is brought to Drupal 8 to provide better security and convenience when doing theming. There is also Twig implementation for JS.
  • This is very simplified scheme of how things will work in D8.
  • Let's imagine that we can use Twig templates on the client side. This means that we can easily re-do some of the front-end functionality with Backbone.js.
  • And it would work for mobile too.
  • Even more, we can wrapp such application in a mobile app with PhoneGap or Those tools allows to build mobile application from HTML5 / CSS3 / JS.
  • Backbone js-slides

    1. 1. Building Bridges, Connecting CommunitiesVADIM MIRGORODFront-end, 05/22/2013Using Backbone.js withDrupal 7 and 8
    2. 2. Vadim Mirgorod• Lead developer in Trellon• Writing Backbone.js CookBook for PACKT• Email:• Web:• Twitter: @dealancer#2
    3. 3. Remember the web development in 90s?#3
    4. 4. 1995: JavaScript#4
    5. 5. 2000: XMLHttpRequest#5
    6. 6. 2006: jQuery#6
    7. 7. 2013:?#7
    8. 8. Whats new in JS?• HTML5:– Local Storage– pushState• JS templating engines:– Mustache.js– Twig.js• Representative State Transfer (REST)#8
    9. 9. JavaScript client evolution#9
    10. 10. Complexity#10
    11. 11. Thin to thick transition#11
    12. 12. Performance#12
    13. 13. Problems!
    14. 14. Right now typical AJAX code looks like this$(document).ready(function() {$("#getData").click( function() {$.getJSON("artistsRemote.cfc?method=getArtists&returnformat=json",function(data) {$("#artistsContent").empty();$("#artistsTemplate").tmpl( data ).appendTo("#artistsContent");var nowIs = new Date().toLocaleString();$(#lastLoad).html( nowIs );});});});#14
    15. 15. AJAX in DrupalHave you seen any JS?#15
    16. 16. #16
    17. 17. Lets do things properly!#17
    18. 18. Meet...#18
    19. 19. #19
    20. 20. Backbone.js• URL:• Created by Jeremy Ashkenas in 2010, an author ofCoffeeScript• Based on Underscore.js:• Requires jQuery or Zepto#20
    21. 21. Backbone.js features• Minimalistic• Modular• Perfect OOP design• Over 100 available extensions:• Community#21
    22. 22. Backbone vs...• Knockout• AngularJS• CanJS• Spine• Ember.js• many others#22
    23. 23. Backbone vs...#23
    24. 24. Who uses Backbone.js?• Groupon Now!• Foursquare• LinkedIn Mobile• Airbnb#24
    25. 25. Lets learn how to backbone!#25
    26. 26. Main concepts• Model• Collection• View• Template• Router• History• Events#26
    27. 27. MVC: Backbone:
    28. 28. DEMO!TODO APP#28
    29. 29. Easy example
    30. 30. Define the model and the collection// Define new model.var InvoiceItemModel = Backbone.Model.extend({calculateAmount: function() {return this.get(price) * this.get(quantity);}});// Define new collection object.var InvoiceItemCollection = Backbone.Collection.extend({model: InvoiceItemModel});#30
    31. 31. Define the view to render the modelvar InvoiceItemView = Backbone.View.extend({// Define element tag name.tagName: tr,// Define template.template: _.template($(#item-row-template).html()),// Render the view.render: function() {var data = this.model.toJSON();data.amount = this.model.calculateAmount();$(this.el).html(this.template(data));return this;},});#31
    32. 32. Define the view to render the collectionvar InvoiceItemListView = Backbone.View.extend({tagName: table,template: _.template($(#item-table-template).html()),// Render the view.render: function() {$(this.el).html(this.template());_.each(this.collection.models, function(model, key){ this.append(model); }, this);return this;},// Add an invoice item row to the table.append: function(model) {$(this.el).append(new InvoiceItemView({ model: model }).render().el);}});#32
    33. 33. Add templates into index.html<script type="text/html" class="template" id="item-table-template"><tr><th>Quantity</th><th>Description</th><th>Price</th><th>Amount</th></tr></script><script type="text/html" class="template" id="item-row-template"><td><%= quantity %></td><td><%= description %></td><td><%= price %></td><td><%= amount %></td>#33
    34. 34. Create collection and show the viewvar invoiceItemCollection = new InvoiceItemCollection([{ description: Wooden Toy House, price: 22, quantity:3 },{ description: Farm Animal Set, price: 17, quantity: 1 },]);$(body).html(new InvoiceItemListView({collection: invoiceItemCollection }).render().el);#34
    35. 35. Some cool thingsTwo way bindingModel to view bindingLayoutsTemplatesRouterForms
    36. 36. Model to view bindingvar InvoiceItemView = Backbone.View.extend({// ...initialize: function() {this.listenTo(this.model, destroy, this.destroy, this);this.listenTo(this.model, change, this.render, this);},destroy: function() { this.remove(); }});var InvoiceItemListView = Backbone.View.extend({// ...initialize: function() {this.listenTo(this.collection, add, this.append, this);}});#36
    37. 37. Forms// Backbone-forms extension.var UserModel = Backbone.Model.extend({schema: {title: { type: Select, options: [Mr, Mrs,Ms] },name: Text,email: { validators: [required, email] },password: Password,birthday: Date,}});userModel = new BuyerModel();$(body).append(new Backbone.Form({ model:this.user }).form.render().el);#37
    38. 38. Two­way binding// Backbone.stickit extension.var InvoiceItemFormView = Backbone.View.extend({className: invoice-item-form-view,bindings: {#description: description,#price: price,#quantity: quantity},render: function() {var html = <label>Description:</label><input type="text"id="description"></input><br> +<label>Price:</label><input type="text" id="price"></input><br> +<label>Quantity:</label><input type="text" id="quantity"></input><br>;$(this.el).html(html);// Here binding occurs.this.stickit();return this;#38
    39. 39. Forms// Backbone-forms extension.var UserModel = Backbone.Model.extend({schema: {title: { type: Select, options: [Mr, Mrs,Ms] },name: Text,email: { validators: [required, email] },password: Password,birthday: Date,}});userModel = new BuyerModel();$(body).append(new Backbone.Form({ model:this.user }).form.render().el);#39
    40. 40. Routervar Workspace = Backbone.Router.extend({routes: {// Default path.: invoiceList,// Usage of static path.invoice: invoiceList,// Usage of fragment parameter.invoice/:id: invoicePage,// Usage of fragment helpPage,// Usage of splat*path: downloadPage},});#40
    41. 41. Other cool Backbone.js Cookbook
    42. 42. • Bootstrapping:– Technique we saw above– Do it yourself• Representational State Transfer:– Services module– RESTful webservices module• Backbone.js moduleBackbone and Drupal 7#43
    43. 43. REST#44
    44. 44. REST in Backbonevar PostModel = Backbone.Model.extend({// Override id attribute.idAttribute: _id,// Define URL root to access model resource. Otherwise use// url() method to provide full path to the model resource.urlRoot: function() { return; }});var PostCollection = Backbone.Collection.extend({model: PostModel,// Define path to the collection resource.url: function() { return; }});#45
    45. 45. REST in Backbone.js// Fetches data into a model.model.fetch();// Saves a;// Destroys a model.model.destroy();// Fetches data into a collection.collection.fetch();// Adds models to a collection.collection.add(models);// Removes specific models from collection.collection.remove(models);#46
    46. 46. Backbone module• URL:• Provides models and collections for Drupal entitiesvia REST:– Node: Node model– All node: NodeIndex collection– Arbitrary view: NodeView collection• Works with both Services and RESTful Web Servicesmodules.#47
    47. 47. Backbone module// Create new NodeView collection.var viewCollection = newDrupal.Backbone.Collections.NodeView();// Set Drupal View name.viewCollection.viewName = backbone_example;// Fetch data from the collection.viewCollection.fetch({success: function() {console.log(viewCollection.toJSON());});#48
    48. 48. Backbone mdl roadmap• Support for bootstrapping• Better views support• In-place content editing• Drag and Drop• D8 version?#49
    49. 49.
    50. 50. Backbone and Drupal 8• It is in core!• Used for In-place editing issue:• Used for layouts issue:• Used for toolbar issue:• META issue:
    51. 51. DEMO!
    52. 52. One more thing!• Web services initiative– REST in core– Storage controllers• Twig– Templating engine– Twig in core (Twig sandbox)– Works both for PHP and JS#53
    53. 53. One more thing!#54Twig templatesStorage controllersAccess controllersRender controllersForm controllersDBBrowser
    54. 54. One more thing!#55Backbone appTwig templatesStorage controllersAccess controllersRender controllersForm controllersDBRESTBrowser
    55. 55. One more thing!#56Backbone appTwig templatesStorage controllersAccess controllersRender controllersForm controllersDBRESTBrowserMobile
    56. 56. One more thing!#57Backbone appTwig templatesStorage controllersAccess controllersDBRESTMobile app built with PhoneGap or
    57. 57. Building Bridges, Connecting CommunitiesEvaluate this session at: Thank you!What did you think?