46
Ember VS Backbone

Ember vs Backbone

  • Upload
    -

  • View
    265

  • Download
    1

Embed Size (px)

DESCRIPTION

Ember vs Backbone

Citation preview

Page 1: Ember vs Backbone

Ember VS Backbone

Page 2: Ember vs Backbone

• Structure overview

• Stand alone JS app

• Using with RoR

Page 3: Ember vs Backbone

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.

Page 4: Ember vs Backbone

Logic is outside of the DOM

Structure logic

Developed for work with REST API’s

Almost MVC - Model, View, Route + Collection

Philosophy

Page 5: Ember vs Backbone

Model

Can be created, validated, destroyed, and saved to the server

!

model.get('attr') model.set('attr', val) model.validate(attributes, options)

Page 6: Ember vs Backbone

There is no two-way data binding between your Backbone Views and Models

But it can be added by using next solutions:

http://rivetsjs.com/

http://nytimes.github.io/backbone.stickit/

Bindings

Page 7: Ember vs Backbone

View

The main idea is to organize your code and give you an opportunity to use different callbacks and events triggers.

Page 8: Ember vs Backbone

elAll 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)

Page 9: Ember vs Backbone

Events

events: 'keyup #tutor-input': 'updatePreview' 'click .submit-tutorial': 'submitTutor' ! 'click #bold': 'boldStyler'

Page 10: Ember vs Backbone

Collections

Is a sortable collection of models, which can filter, manage and control them.

Accessing models:

collection.models collection.at collection.get

Page 11: Ember vs Backbone

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

Page 12: Ember vs Backbone

RoutesHash navigation - localhost#search/users/2

!

class Tutors.Routers.Tutorials.New extends Backbone.Router routes: '.*': 'addTutor' 'addTutor': 'addTutor'

Page 13: Ember vs Backbone

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); } });

Page 14: Ember vs Backbone

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

Page 15: Ember vs Backbone

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); !

!

Page 16: Ember vs Backbone

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

Page 17: Ember vs Backbone

Benefits1) 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/

Page 18: Ember vs Backbone
Page 19: Ember vs Backbone

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 and Yehuda Katz say it’s easy to see when a site is using Ember because of its loading speed.

69K minified and zipped

Page 20: Ember vs Backbone

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

Page 21: Ember vs Backbone

CORE CONCEPTS

• TEMPLATES

• ROUTER

• COMPONENTS

• MODELS

• CONTROLLERS

• VIEWS

Page 22: Ember vs Backbone

When your application boots, Ember will look for these objects:!!!

App.ApplicationRoute!App.ApplicationModel!

App.ApplicationController!the application template!

Page 23: Ember vs Backbone

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

Page 24: Ember vs Backbone

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.

Page 25: Ember vs Backbone

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>

Page 26: Ember vs Backbone

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.

Page 27: Ember vs Backbone

<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}}

Page 28: Ember vs Backbone

<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

Page 29: Ember vs Backbone

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);

Page 30: Ember vs Backbone

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-MANYApp.Post = DS.Model.extend({ tags: DS.hasMany('tag') }); !App.Tag = DS.Model.extend({ posts: DS.hasMany('post') });

Page 31: Ember vs Backbone

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

Page 32: Ember vs Backbone

ADAPTERS

App.PostAdapter = DS.RESTAdapter.extend({ namespace: 'api/v1' });

Page 33: Ember vs Backbone

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.

Page 34: Ember vs Backbone

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>

Page 35: Ember vs Backbone

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.

Page 36: Ember vs Backbone

VIEWSViews 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');

Page 37: Ember vs Backbone

Handling events

{{#view App.ClickableView}} This is a clickable area! {{/view}} !!App.ClickableView = Ember.View.extend({ click: function(evt) { alert("ClickableView was clicked!"); } });

Page 38: Ember vs Backbone

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>

RESULTUser: Albert Hofmann <div> <b>Posts:</b> 25 <br> <b>Hobbies:</b> Riding bicycles </div>

Page 39: Ember vs Backbone

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.

Page 40: Ember vs Backbone

Stand alone JS app

http://yeoman.io/

Page 41: Ember vs Backbone

Backbone.js generator

• npm install -g generator-backbone

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

• yo backbone [app-name]

!

https://github.com/yeoman/generator-backbone

Page 42: Ember vs Backbone

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

Page 43: Ember vs Backbone

Rails + JS Framework

• Backbone on Rails

• ember-rails

Page 44: Ember vs Backbone

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/

Page 45: Ember vs Backbone

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

Page 46: Ember vs Backbone

QUESTIONS?