Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Ember VS Backbone
• Structure overview	

• Stand alone JS app	

• Using with RoR
Backbone came out in June 2010	

Many popular applications use the Backbone framework,
including Twitter, Foursquare, and ...
Logic is outside of the DOM	

Structure logic	

Developed for work with REST API’s	

Almost MVC - Model,View, Route + Coll...
Model
Can be created, validated, destroyed, and saved to the
server	

!
model.get('attr')
model.set('attr', val)
model.val...
There is no two-way data binding between your
BackboneViews and Models	

But it can be added by using next solutions:	

ht...
View
The main idea is to organize your code and give you an
opportunity to use different callbacks and events
triggers.
el
All views have a DOM element at all times (the el
property), whether they've already been inserted into
the page or not...
Events
events:
'keyup #tutor-input': 'updatePreview'
'click .submit-tutorial': 'submitTutor'
!
'click #bold': 'boldStyler'
Collections
Is a sortable collection of models, which can filter,
manage and control them.	

Accessing models:	

collection...
collection.add([{key: val}, {key: val}])	

collection.remove	

collection.set	

collection.get(id)	

colleaction.at(index)...
Routes
Hash navigation - localhost#search/users/2	

!
class Tutors.Routers.Tutorials.New extends
Backbone.Router
routes:
'...
navigate router.navigate(fragment, [options])
!
!
!
!
Execute method is called internally within the
router:
var Router = ...
History serves as a global router to handle hashchange
events, match the appropriate route, and trigger
callbacks.You shou...
Events
Events is a module that can be mixed in to any object, giving the object the ability to bind and
trigger custom nam...
Catalog of Events	

• "add" (model, collection, options) — when a model is added to a collection.	

• "remove" (model, col...
Benefits
1) Standatized architecture of application, which will be very friendly for rails developers	

2) Easy scallable a...
Initially released in 2011, Ember just hit version 1.0 last year.	

LivingSocial, Groupon, Zendesk, Discourse, and Square ...
The first step to creating an Ember.js application is to
make an instance of Ember.Application and assign it to a
global va...
CORE CONCEPTS
• TEMPLATES	

• ROUTER	

• COMPONENTS	

• MODELS	

• CONTROLLERS	

• VIEWS
When your application boots, Ember will look for these objects:!
!
!
App.ApplicationRoute!
App.ApplicationModel!
App.Appli...
A template, written in the Handlebars templating language, describes the user interface of your application.
Each template...
Router
The router translates a URL into a series of nested templates, each backed
by a model.As the templates or models be...
App.Router.map(function() {
this.route("about", { path: "/about" });
this.route("favorites", { path: "/
favs" });
});
!
No...
COMPONENTS
A component is a custom HTML tag whose behavior
you implement using JavaScript and whose appearance
you describ...
<script type="text/x-handlebars" id="components/blog-post">
<h1>Blog Post</h1>
<p>Lorem ipsum dolor sit amet.</p>
</script...
<script type="text/x-handlebars" id="components/blog-post">
<h1>Component: {{title}}</h1>
<p>Lorem ipsum dolor sit amet.</...
MODELS
A model is an object that stores persistent state.
Templates are responsible for displaying the model to
the user b...
ONE-TO-ONE	

App.User = DS.Model.extend({
profile: DS.belongsTo('profile')
});
!
App.Profile = DS.Model.extend({
user: DS....
store.createRecord('post', {
title: 'Rails is Omakase',
body: 'Lorem ipsum'
});
store.find('post', 1).then(function (post)...
ADAPTERS
App.PostAdapter = DS.RESTAdapter.extend({
namespace: 'api/v1'
});
CONTROLLERS
A controller is an object that stores application state.A
template can optionally have a controller in additio...
REPRESENTING A
SINGLE MODEL
App.SongController =
Ember.ObjectController.extend({
soundVolume: 1
});
<p>
<strong>Song</stro...
REPRESENTING
MULTIPLE MODELS
App.SongsController = Ember.ArrayController.extend({
longSongCount: function() {
var longSong...
VIEWS
Views in Ember.js are typically only created for the following
reasons:	

• When you need sophisticated handling of ...
Handling events
{{#view App.ClickableView}}
This is a clickable area!
{{/view}}
!
!
App.ClickableView = Ember.View.extend(...
INSERTING VIEWS IN TEMPLATES
// Define parent view
App.UserView = Ember.View.extend({
templateName: 'user',
!
firstName: "...
Benefits
• Two-way data binding: objects in Ember are able to
register bindings between one another.That way,
whenever a bo...
Stand alone JS app
http://yeoman.io/
Backbone.js generator
• npm install -g generator-backbone	

• mkdir my-new-project && cd $_	

• yo backbone [app-name]	

!...
Ember.js Generator
• npm install -g generator-ember	

• mkdir myemberapp && cd myemberapp(The
directory's name is your app...
Rails + JS Framework
• Backbone on Rails	

• ember-rails
Backbone on Rails
gem 'backbone-on-rails'	

bundle install	

rails generate backbone:install	

rails generate backbone:sca...
Ember on Rails
gem 'ember-rails'	

gem 'ember-source', '1.5.0' # or the version you need	

bundle install	

rails g ember:...
QUESTIONS?
Ember vs Backbone
Upcoming SlideShare
Loading in …5
×

Ember vs Backbone

874 views

Published on

Ember vs Backbone

Published in: Software
  • Be the first to comment

  • Be the first to like this

Ember vs Backbone

  1. 1. Ember VS Backbone
  2. 2. • Structure overview • Stand alone JS app • Using with RoR
  3. 3. Backbone came out in June 2010 Many popular applications use the Backbone framework, including Twitter, Foursquare, and LinkedIn Mobile.Also worth noting is that a number of music apps were built with Backbone, including Soundcloud, Pitchfork, and Pandora. Backbone weight just 6.4K.
  4. 4. Logic is outside of the DOM Structure logic Developed for work with REST API’s Almost MVC - Model,View, Route + Collection Philosophy
  5. 5. Model Can be created, validated, destroyed, and saved to the server ! model.get('attr') model.set('attr', val) model.validate(attributes, options)
  6. 6. There is no two-way data binding between your BackboneViews and Models But it can be added by using next solutions: http://rivetsjs.com/ http://nytimes.github.io/backbone.stickit/ Bindings
  7. 7. View The main idea is to organize your code and give you an opportunity to use different callbacks and events triggers.
  8. 8. el All views have a DOM element at all times (the el property), whether they've already been inserted into the page or not. ! ! template: JST[‚tutorials/new_tutor'] ! var BodyView = Backbone.View.extend({ el: 'body' }); ! @$el.html(@template)
  9. 9. Events events: 'keyup #tutor-input': 'updatePreview' 'click .submit-tutorial': 'submitTutor' ! 'click #bold': 'boldStyler'
  10. 10. Collections Is a sortable collection of models, which can filter, manage and control them. Accessing models: collection.models collection.at collection.get
  11. 11. collection.add([{key: val}, {key: val}]) collection.remove collection.set collection.get(id) colleaction.at(index) collection.push(model, [options]) collection.pop(model, [options]) collection.pluck(“attr”) collection.where({job:‘Some’}) ! collection.fetch ! Underscore methods: find, contains, sortBy, groupBy, toArray, size, first, last, indexOf, isEmpty
  12. 12. Routes Hash navigation - localhost#search/users/2 ! class Tutors.Routers.Tutorials.New extends Backbone.Router routes: '.*': 'addTutor' 'addTutor': 'addTutor'
  13. 13. navigate router.navigate(fragment, [options]) ! ! ! ! Execute method is called internally within the router: var Router = Backbone.Router.extend({ execute: function(callback, args) { args.push(parseQueryString(args.pop())); if (callback) callback.apply(this, args); } });
  14. 14. History serves as a global router to handle hashchange events, match the appropriate route, and trigger callbacks.You shouldn't ever have to create one of these yourself since Backbone.history already contains one. Just call it like this - Backbone.history.start Backbone.history
  15. 15. Events Events is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events. book.on({ "change:title": titleView.update, "change:author": authorPane.update, "destroy": bookView.remove }); ! // Removes just the `onChange` callback. object.off("change", onChange); ! view.listenTo(model, 'change', view.render); !
  16. 16. Catalog of Events • "add" (model, collection, options) — when a model is added to a collection. • "remove" (model, collection, options) — when a model is removed from a collection. • "reset" (collection, options) — when the collection's entire contents have been replaced. • "sort" (collection, options) — when the collection has been re-sorted. • "change" (model, options) — when a model's attributes have changed. • "change:[attribute]" (model, value, options) — when a specific attribute has been updated. • "destroy" (model, collection, options) — when a model is destroyed. • "request" (model_or_collection, xhr, options) — when a model or collection has started a request to the server. • "sync" (model_or_collection, resp, options) — when a model or collection has been successfully synced with the server. • "error" (model_or_collection, resp, options) — when model's or collection's request to remote server has failed. • "invalid" (model, error, options) — when a model's validation fails on the client. • "route:[name]" (params) — Fired by the router when a specific route is matched. • "route" (route, params) — Fired by the router when any route has been matched. • "route" (router, route, params) — Fired by history when any route has been matched. • "all" — this special event fires for any triggered event, passing the event name as the first
  17. 17. Benefits 1) Standatized architecture of application, which will be very friendly for rails developers 2) Easy scallable and refactoring 3) A lot of methods for working with events, callbacks, models and collections With Backbone, you have some given assertions: Data lies in JavaScript objects, not the DOM Event handling lies in JavaScript objects, not jQuery event bindings The way you save data in a backend server is done through the objects that contain the data http://backbonejs.org/
  18. 18. Initially released in 2011, Ember just hit version 1.0 last year. LivingSocial, Groupon, Zendesk, Discourse, and Square are some of the most well-known applications that have adopted Ember. Ember creators Tom Dale andYehuda Katz say it’s easy to see when a site is using Ember because of its loading speed. 69K minified and zipped
  19. 19. The first step to creating an Ember.js application is to make an instance of Ember.Application and assign it to a global variable. ! window.App = Ember.Application.create(); ! INITIALIZING AN APPLICATION
  20. 20. CORE CONCEPTS • TEMPLATES • ROUTER • COMPONENTS • MODELS • CONTROLLERS • VIEWS
  21. 21. When your application boots, Ember will look for these objects:! ! ! App.ApplicationRoute! App.ApplicationModel! App.ApplicationController! the application template!
  22. 22. A template, written in the Handlebars templating language, describes the user interface of your application. Each template is backed by a model, and the template automatically updates itself if the model changes. In addition to plain HTML, templates can contain: • Expressions, like {{firstName}}, which take information from the template's model and put it into HTML. • Outlets, which are placeholders for other templates.As users move around your app, different templates can be plugged into the outlet by the router.You can put outlets into your template using the {{outlet}} helper. • Components, custom HTML elements that you can use to clean up repetitive templates or create reusable controls. Templates
  23. 23. Router The router translates a URL into a series of nested templates, each backed by a model.As the templates or models being shown to the user change, Ember automatically keeps the URL in the browser's address bar up-to-date. A route is an object that tells the template which model it should display. Each of your routes will have a controller, and a template with the same name as the route.
  24. 24. App.Router.map(function() { this.route("about", { path: "/about" }); this.route("favorites", { path: "/ favs" }); }); ! Now, when the user visits /about, Ember.js will render the about template. Visiting /favs will render the favorites template. {{#link-to 'index'}}<img class="logo">{{/link-to}} ! <nav> {{#link-to 'about'}}About{{/link-to}} {{#link-to 'favorites'}}Favorites{{/link-to}} </nav>
  25. 25. COMPONENTS A component is a custom HTML tag whose behavior you implement using JavaScript and whose appearance you describe using Handlebars templates. They allow you to create reusable controls that can simplify your application's templates.
  26. 26. <script type="text/x-handlebars" id="components/blog-post"> <h1>Blog Post</h1> <p>Lorem ipsum dolor sit amet.</p> </script> ! <h1>My Blog</h1> {{#each}} {{blog-post}} {{/each}}
  27. 27. <script type="text/x-handlebars" id="components/blog-post"> <h1>Component: {{title}}</h1> <p>Lorem ipsum dolor sit amet.</p> </script> ! ! App.IndexRoute = Ember.Route.extend({ model: function() { return { title: "Rails is awesome!" }; } }); ! ! {{blog-post title=title}} Passing an arguments
  28. 28. MODELS A model is an object that stores persistent state. Templates are responsible for displaying the model to the user by turning it into HTML. In many applications, models are loaded via an HTTP JSON API, although Ember is agnostic to the backend that you choose. App.Person = DS.Model.extend(); ! store.find('person', 1);
  29. 29. ONE-TO-ONE App.User = DS.Model.extend({ profile: DS.belongsTo('profile') }); ! App.Profile = DS.Model.extend({ user: DS.belongsTo('user') }); ONE-TO-MANY App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); ! App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); MANY-TO-MANY App.Post = DS.Model.extend({ tags: DS.hasMany('tag') }); ! App.Tag = DS.Model.extend({ posts: DS.hasMany('post') });
  30. 30. store.createRecord('post', { title: 'Rails is Omakase', body: 'Lorem ipsum' }); store.find('post', 1).then(function (post) { post.deleteRecord(); post.get('isDeleted'); // => true post.save(); // => DELETE to /posts/1 }); ! // OR store.find('post', 2).then(function (post) { post.destroyRecord(); // => DELETE to /posts/2 }); DELETING RECORDS CREATING RECORDS
  31. 31. ADAPTERS App.PostAdapter = DS.RESTAdapter.extend({ namespace: 'api/v1' });
  32. 32. CONTROLLERS A controller is an object that stores application state.A template can optionally have a controller in addition to a model, and can retrieve properties from both.
  33. 33. REPRESENTING A SINGLE MODEL App.SongController = Ember.ObjectController.extend({ soundVolume: 1 }); <p> <strong>Song</strong>: {{name}} by {{artist}} </p> <p> <strong>Current Volume</strong>: {{soundVolume}} </p>
  34. 34. REPRESENTING MULTIPLE MODELS App.SongsController = Ember.ArrayController.extend({ longSongCount: function() { var longSongs = this.filter(function(song) { return song.get('duration') > 30; }); return longSongs.get('length'); }.property('@each.duration') }); ! ! ! <ul> {{#each}} <li>{{name}} by {{artist}}</li> {{/each}} </ul> ! {{longSongCount}} songs over 30 seconds.
  35. 35. VIEWS Views in Ember.js are typically only created for the following reasons: • When you need sophisticated handling of user events • When you want to create a re-usable component var view = Ember.View.create({ templateName: 'say-hello', name: "Bob" }); ! ! view.appendTo('#container');
  36. 36. Handling events {{#view App.ClickableView}} This is a clickable area! {{/view}} ! ! App.ClickableView = Ember.View.extend({ click: function(evt) { alert("ClickableView was clicked!"); } });
  37. 37. INSERTING VIEWS IN TEMPLATES // Define parent view App.UserView = Ember.View.extend({ templateName: 'user', ! firstName: "Albert", lastName: "Hofmann" }); ! // Define child view App.InfoView = Ember.View.extend({ templateName: 'info', ! posts: 25, hobbies: "Riding bicycles" }); ! <script type="text/x-handlebars" data-template-name="user"> User: {{view.firstName}} {{view.lastName}} {{view App.InfoView}} </script> ! <script type="text/x-handlebars" data-template-name="info"> <b>Posts:</b> {{view.posts}} <br> <b>Hobbies:</b> {{view.hobbies}} </script> RESULT User: Albert Hofmann <div> <b>Posts:</b> 25 <br> <b>Hobbies:</b> Riding bicycles </div>
  38. 38. Benefits • Two-way data binding: objects in Ember are able to register bindings between one another.That way, whenever a bound property changes, the other one is updated automatically. • Computed properties: if you wish to have a property that is a result of a function, you can create them and assign a property as computed by that function. • Template auto-updates: when an object is updated in your app, all the views currently displayed in the screen that are bound to that object automatically reflect the change, with no boilerplate.
  39. 39. Stand alone JS app http://yeoman.io/
  40. 40. Backbone.js generator • npm install -g generator-backbone • mkdir my-new-project && cd $_ • yo backbone [app-name] ! https://github.com/yeoman/generator-backbone
  41. 41. Ember.js Generator • npm install -g generator-ember • mkdir myemberapp && cd myemberapp(The directory's name is your application's name) • yo ember • npm install -g grunt-mocha • grunt serve
  42. 42. Rails + JS Framework • Backbone on Rails • ember-rails
  43. 43. Backbone on Rails gem 'backbone-on-rails' bundle install rails generate backbone:install rails generate backbone:scaffold NAME https://github.com/meleyal/backbone-on-rails http://moxa.ws/en/adding-backbone-js-in-rails-app-in-5- seconds/
  44. 44. Ember on Rails gem 'ember-rails' gem 'ember-source', '1.5.0' # or the version you need bundle install rails g ember:bootstrap -g --javascript-engine coffee ! https://github.com/emberjs/ember-rails
  45. 45. QUESTIONS?

×