40
Angular or Backbone: Go Mobile! Doris Chen Ph.D. Senior Developer Evangelist Microsoft [email protected] http://blogs.msdn.com/dorischen/ @doristchen

Angular or Backbone: Go Mobile!

Embed Size (px)

DESCRIPTION

Angular or Backbone, which one you will use in your mobile app? How could you develop a mobile app across iOS, Android or windows devices? This talk will take an intimate look at two of today’s most popular frameworks, Angular and Backbone and explore their differences. We’ll show how Apache Cordova opens the world of mobile app development to web developers. In the session, we will demonstrate a “To Do” app using Angular and Backbone, with access to native device capabilities. We’ll compare the frameworks when transported to the world of mobile app development. Along the way, you'll also learn what kind of apps are best-suited for the hybrid architecture and when to make the switch from web app to mobile app.

Citation preview

Page 1: Angular or Backbone: Go Mobile!

Angular or Backbone: Go Mobile!

Doris Chen Ph.D.

Senior Developer Evangelist

Microsoft

[email protected]

http://blogs.msdn.com/dorischen/

@doristchen

Page 2: Angular or Backbone: Go Mobile!

Doris Chen, Ph.D.

• Developer Evangelist at Microsoft based in Silicon Valley, CA

• Blog: http://blogs.msdn.com/b/dorischen/

• Twitter @doristchen

• Email: [email protected]

• Over 18 years of experience in the software industry focusing on web technologies

• Spoke and published widely at O'Reilly OSCON, Fluent, HTML5 Dev Conf, JavaOne, Google Developer Conference, Silicon Valley Code Camp and worldwide User Groups meetups

• Doris received her Ph.D. from the University of California at Los Angeles (UCLA)

Page 3: Angular or Backbone: Go Mobile!

Agenda

1. Angular vs Backbone

2. Demo: ToDo App in Angular and Backbone

3. Mobile Apps for JavaScript

4. Demo: ToDo App with Apache Cordova

5. Summary and Resources

Page 4: Angular or Backbone: Go Mobile!

Angular vs Backbone

Page 5: Angular or Backbone: Go Mobile!

Angular vs Backbone: common

• Client-side framework using the MV* design pattern

• Solve the problem of Single Page Web Applications• Structure

• Modular

• Support multiple clients

• Both open-sourced, under the permissive MIT license

• Have the concept of views, events, data models and routing

Page 6: Angular or Backbone: Go Mobile!

History

Angular

• Born in 2009 as a part of commercial product, called GetAngular

• Misko Hevery, one of founders, turn a web application• 17,000 lines in 6 months to 1,000 lines

in 3 weeks using just GetAngular

• Google starts sponsoring, becomes open-source Angular.js

Backbone

• Born in 2010, lightweight MVC framework/library

• As a lean alternative to heavy, full-featured MVC (MVVC) frameworks such as ExtJS

Page 7: Angular or Backbone: Go Mobile!

Learning curve and Flexibility

Angular

• Looks quite easy at first sight • After the very basics it is quite a steep

learning curve from there

• Highly opinionated• Fighting the framework if you don’t

like the way it does certain things

• Reading the documentation is not easy as a lot of Angular specific jargon

• Lack of examples

Backbone

• Basic of backbone is very easy to learn

• Not opinionated• most flexible framework with the less

conventions and opinions

• Need to make a lot of decisions when using Backbone

• Need to watch or read a few tutorials to learn some best Backbone practices

• probably need to learn another library on top of Backbone (e.g. Marionette or Thorax)

Page 8: Angular or Backbone: Go Mobile!

Community

Metric Angular Backbone

Stars on GitHub 29.8k 19.3k

Third-Party Modules 800 ngmodules 236 backplugs

StackOverflow Questions 49.5k 15.9k

YouTube Results ~75k ~16k

GitHub Contributors 928 230

Chrome Extension Users 150k 7k

Page 9: Angular or Backbone: Go Mobile!

Angular Backbone

Architecture MV* (Model View Whatever) MV + VC

Template Support YES. doesn’t require any other separate template engine.(Also doesn’t support template engine)

Uses underscore.js( an embedded template engine which allows logic inside template code)

File Size 39.5K (no dependencies) 6.5K - 43.5K (w/underscore & jQuery)

Nested Template Support Yes No

Data Binding Yes No

Routing Yes Yes

Compatible with other frameworks

Yes Yes

Additional Features Dependency Injection, Directives, Watch Expressions and 2-way Binding, HTML5 validations, Form Validations, and Filtering

Page 10: Angular or Backbone: Go Mobile!

Angular: templates

• Simply HTML with binding expressions baked-in

• Binding expressions are surrounded by double curly braces<ul>

<li ="framework in frameworks"

title="{{framework.description}}">

{{framework.name}}

</li>

</ul>

Page 11: Angular or Backbone: Go Mobile!

Backbone: templates

<ul>

<% _.each(frameworks, function(framework) { %>

<li title="<%- framework.description %>">

<%- framework.name %>

</li>

<% }); %>

</ul>

Underscore is very basic and you usually have to throw JavaScript into the mix

Page 12: Angular or Backbone: Go Mobile!

Angular: model

• Angular does not use observable properties, no restriction on implementing model

• No class to extend and no interface to comply

• Free to use whatever you want (including existing Backbone models)

• In practice, most developers use plain old JavaScript objects (POJO)

Page 13: Angular or Backbone: Go Mobile!

Backbone: model

app.TodoModel = Backbone.Model.extend({

defaults: {

title: '',

done: false,

location: 'Getting your location...'

},

toggleCompleted: function () {

this.save({

done: !this.get('done')

});

},

sync: function () { return false; }

});

Page 14: Angular or Backbone: Go Mobile!

Backbone: model and collection

var TodoCollection = Backbone.Collection.extend({

model: app.TodoModel,

});

app.todoCollection = new TodoCollection;

• Backbone is built around observable properties, forced to extend Backbone.Model and Backbone.Collection

• Backbone does not support observing functions, property needs to reset when any change happens

Page 15: Angular or Backbone: Go Mobile!

Angular: good things

• Two-way data bindings, dependency injection, easy-to-test code, extending the HTML dialect by using directives, out of the box filters, reusable services and factories

• Minimizes drastically the boilerplate code, no direct DOM manipulation

• The automatic Dirty Checking• No need getters and setters

• modify property and angular automatically detects the change and notify all the watchers

Page 16: Angular or Backbone: Go Mobile!

2-way bindings and directives

<div class="templateWrapper" ng-repeat="toDoItem in todos">

<div class="templateContainer">

<input class="templateTitle"

ng-class="{crossedOut: toDoItem.done}" type="text"

ng-text-change="changeToDoText(toDoItem)"

ng-model="toDoItem.text" />

<h3 class="templateAddress">{{toDoItem.address}}</h3>

</div>

</div>

Page 17: Angular or Backbone: Go Mobile!

Dependency injection

<section id="todoapp" ng-controller="ToDoCtrl"> <button class="templateLeft templateRemove"ng-click="removeToDo(toDoItem)"></button>

</section>

angular.module("xPlat.controllers").controller('ToDoCtrl', ['$scope', 'maps', 'storage',

function ($scope, maps, storage) {$scope.removeToDo = function (toDoItem) {

storage.del(toDoItem).then(function (todo) {var index = $scope.todos.indexOf(todo);$scope.todos.splice(index, 1);

});}

}]);

Page 18: Angular or Backbone: Go Mobile!

Angular: more good things

• Building application blocks into: Controllers, Directives, Factories, Filters, Services and Views (templates). • Views UI, Controllers logic behind UI, Services communication with

backend and common functionality, Directives reusable components and extending HTML by defining new elements, attributes and behaviors

• Promises play a main role in Angular

Page 19: Angular or Backbone: Go Mobile!

Custom directives

<input class="templateTitle"ng-class="{crossedOut: toDoItem.done}" type="text"ng-text-change=" changeToDoText(toDoItem)"ng-model="toDoItem.text" />

angular.module('xPlat.directives').directive('ngTextChange', function () {

return {restrict: 'A',replace: 'ngModel',link: function (scope, element, attr) {

element.on('change', function () {scope.$apply(function () {

scope.$eval(attr.ngTextChange);});

…});

Page 20: Angular or Backbone: Go Mobile!

Custom directives, continued

$scope.changeToDoText = function (toDoItem) {//Notice .then Promise pattern is used heregetAddress().then(function (address) {

toDoItem.address = address;return storage.update(toDoItem);

}, function (errorMessage) {toDoItem.address = errorMessage;return storage.update(toDoItem);

});}

Page 21: Angular or Backbone: Go Mobile!

Angular: bad things

• Extremely opinionated• Frustrated: prior experience in creating UI with Javascript is rendered almost useless

• Do everything according to the “Angular way”

• Directives could be super complicated and odd

• Expression language too powerful• <button ng-click="(oldPassword && checkComplexity(newPassword) && oldPassword != newPassword) ? (changePassword(oldPassword, newPassword) && (oldPassword=(newPassword=''))) : (errorMessage='Please input a new password matching the following requirements: ' + passwordRequirements)">Click me</button>

Page 22: Angular or Backbone: Go Mobile!

Backbone: good things

• Compact, minimal, not opinionated

• Resembles classic Javascript the most

• Has the least learning curve

• Huge community (ecosystem) and lots of solutions on StackOverflow

• Many popular applications • Twitter, Foursquare, LinkedIn Mobile, Soundcloud, Pitchfork, Pandora,

Pinterest, Flixster, AirBNB

Page 23: Angular or Backbone: Go Mobile!

Backbone: bad things

• Hands off: Need to develop own • Application Architecture / Layout Structure / Memory management/

• Too much option of bringing third party plugins• Cost time to do research, it’s not so minimal and becomes opinionated

• Lacking features compared to the newer frameworks• No data binding

• a lot of boiler plate code to make it work well

• doesn’t allow easy iteration through UI variants

• No nested model• userModel.get("name").first = "Tom"; userModel.set("name.first","Tom"); -- can’t do

• Views manipulate the DOM directly, making them really hard to unit-test, more fragile and less reusable.

Page 24: Angular or Backbone: Go Mobile!

Backbone vs Angular

updateCrossOut: function () {if (this.model.get('done')) {

this.$input.addClass('crossedOut');… …

}else {

this.$input.removeClass('crossedOut');… …

}},

<input class="templateTitle"ng-class="{crossedOut: toDoItem.done}"… ng-model="toDoItem.text" />

Page 25: Angular or Backbone: Go Mobile!

Performance Comparison: TodoMVC Benchmark

• Angular (v1.2.14), Backbone (v1.1.2) + jQuery (v2.1.0)

• Test case: • Add 100 todos, toggle them one by one, then delete them one by one,

• 10 runs average • Data collected on an Late 2013 Retina Macbook Pro 13 with a 2.6GHz dual-core i5-4288U

Processor under OS X Mavericks 10.9.1.

• Average Response on Chrome 33, Firefox 28 and Safari 7

• AngularJS 1617.72ms

• Backbone 833.36ms

• http://vuejs.org/perf/

Page 26: Angular or Backbone: Go Mobile!

DemoToDo MVC in Angular and Backbone

Page 27: Angular or Backbone: Go Mobile!

When to use Angular?

• Something declarative that uses View to derive behavior

• Custom HTML tags and components that specify your application intentions

• Easily testable, URL management (routing) and a separation of concerns through a variation of MVC

• Good at making quick changes• create easily testable code and test it often

• Not a good fit for Angular• Games and GUI editors are examples of applications with intensive and tricky

DOM manipulation, different from CRUD apps• may be better to use a library like jQuery

• Has its own scaffolding tools available (angular-seed)

Page 29: Angular or Backbone: Go Mobile!

Go mobileFrom web app to hybrid app

Page 30: Angular or Backbone: Go Mobile!

Apps dominate the mobile web

Page 31: Angular or Backbone: Go Mobile!

Low investment for more capabilities

Capabilities

Deve

lop

er

Inve

stm

ent

Web App

Hybrid App

Native App

Page 32: Angular or Backbone: Go Mobile!

World Wide Web Hybrid

Delivery mechanism Delivered via browser Packaged on my device

Input Touch Touch

Offline Support No Yes

Device Capabilities Web APIs Only Native Device APIs

Monetization Web Commerce App Store & In-App Purchases

Discoverability Bookmarks & Search Engines Always on my home screen

🌐

Page 33: Angular or Backbone: Go Mobile!

What is Apache Cordova?

• Open-source framework

Page 34: Angular or Backbone: Go Mobile!

Native WrapperWhat is Apache Cordova?

• Open-source framework

• Hosted webview

• Single, shared codebase deployed to all targets

<webview>

Your JavaScript App

Page 35: Angular or Backbone: Go Mobile!

Native WrapperWhat is Apache Cordova?

• Open-source framework

• Hosted webview

• Single, shared codebase deployed to all targets

• Plugins provide a common JavaScript API to access device capabilities

<webview>

Your JavaScript App

Cordova Plugin JS API

Page 36: Angular or Backbone: Go Mobile!

Native WrapperWhat is Apache Cordova?

• Open-source framework

• Hosted webview

• Single, shared codebase deployed to all targets

• Plugins provide a common JavaScript API to access device capabilities

• About 6% of apps in stores (13% in enterprise)

<webview>

Your JavaScript App

Cordova Plugin JS API

Page 37: Angular or Backbone: Go Mobile!

DemoConverting ToDo MVC into a hybrid app

Page 38: Angular or Backbone: Go Mobile!

Tips, Tricks & Considerations

• Use Cordova when an idea makes sense as a web app, but you need…• Cross-platform support as a packaged application• Offline support • Access to native device capabilities (e.g. camera, accelerometer, file system)• Better reach & discoverability

• If you’re building a first-person shooter… go native.

• Cordova depends on the platform build system• To build for iOS, you need a Mac• To build for Windows 8+, you need Windows 8+• To build for Android, you need the Android SDK

• Touch input means bigger everything. Consider a control framework like Ionic.

Page 39: Angular or Backbone: Go Mobile!

Summary

• Backbone was easier to learn compared to Angular

• Backbone tends to be faster than Angular in ToDoMVC perftests

• Angular resulted in fewer lines code than Backbone for our app making it easier to maintain

• Angular provided far more features (e.g. data-binding, custom directives, declarative markup)

• Converting both frameworks to mobile was equally simple via Apache Cordova

Page 40: Angular or Backbone: Go Mobile!

Resources

• AngularJS: http://angularjs.org

• BackboneJS: http://backbonejs.org

• ToDo MVC: http://todomvc.com

• Tools for Apache Cordova: http://aka.ms/cordova

• StackOverflow #multi-device-hybrid-apps