20. Backbone.js
• URL: http://backbonejs.org/
• Created by Jeremy Ashkenas in 2010, an author of
CoffeeScript
• Based on Underscore.js: http://backbonejs.org/
• Requires jQuery or Zepto
#20
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. Define the view to
render the model
var 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. Define the view to
render the collection
var 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
45. REST in Backbone
var 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 'http://example.com/posts/'; }
});
var PostCollection = Backbone.Collection.extend({
model: PostModel,
// Define path to the collection resource.
url: function() { return 'http://example.com/posts/'; }
});
#45
46. REST in Backbone.js
// Fetches data into a model.
model.fetch();
// Saves a model.
model.save();
// 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
47. Backbone module
• URL: http://drupal.org/project/backbone
• Provides models and collections for Drupal entities
via REST:
– Node: Node model
– All node: NodeIndex collection
– Arbitrary view: NodeView collection
• Works with both Services and RESTful Web Services
modules.
#47
48. Backbone module
// Create new NodeView collection.
var viewCollection = new
Drupal.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
51. Backbone and Drupal 8
• It is in core!
• Used for In-place editing issue:
http://drupal.org/node/1824500
• Used for layouts issue:http://drupal.org/node/1841584
• Used for toolbar issue:http://drupal.org/node/1860434
• META issue: http://drupal.org/node/1858368
#51
53. 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
58. Building Bridges, Connecting Communities
Evaluate this session at:
portland2013.drupal.org/node/1578.
Thank you!
What did you think?
Notas do Editor
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 Trigger.io. Those tools allows to build mobile application from HTML5 / CSS3 / JS.