adventure time with javascript & single page applications
DESCRIPTION
with Carl Bergenhem Presented at Web Unleashed 2013 in Boston on Nov 7-8, 2013. We’ve all seen the phrase ‘Single Page Application’ or ‘SPA’ everywhere and everyone talks about how they’re the best thing since sliced bread, but what is an SPA really? Why are they the cat’s pajamas? In this session Carl will take a look at a few of the popular SPA frameworks out there: AngularJS, BackBoneJS, and Kendo UI. He will also cover what a SPA does in general, what makes each one of these libraries unique, and how they can be utilized in your web development today.TRANSCRIPT
Adventure Timewith
JavaScript & Single Page Apps - Web Unleashed 2013 - Carl Bergenhem @carlbergenhem
IntroductionsCarl Bergenhem
Manager, Solutions Consultants
Telerik
@carlbergenhem
Quick Notes
Covering a lot of ground today
High level overview
More code in tomorrow'sworkshop
9 AM - 12:30 PM @ Room 325 BC
What is a SPA?
Single Page Application
A web app that fits in a singlepage
Entire app is loaded at once
Built with a MV* Framework
Server provides the initial app
Section our HTML page in views
Get data via RESTful requests
Bind the data to our UI
Business logic in our MV*framework
MV* framework handles URLrequests
Why SPA?
Create desktop-like apps in theweb
Increase responsiveness
Reduce loadtime of pages
Less time spent on the server
Control user interactions on theclient
Improved end-user experience
History
In the BeginningReign of the post back
Everything done on the server
Full page refreshes
We got wiserAjax & XHR Requests
Serve some content via server
Do asynchronous calls to server
Partial page refreshes
Focus onresponsivenessIntroduce the SPA concept
Move all items over to the client
What makes up aSPA?
MV* Framework
Basic pieces of a MV*ModelView*
A full SPA framework also hasRouting
Model
In charge of holding data
Communication with server
Work with server end-points
Define what data should beused
Controller
Control applications'StateLogicBehavior
Custom business logic
Communicate between theView and Model
Provide validation
Bind data to our Views (UI)
View
Responsible for the UI of ourapp
Modifies and interacts with ourDOM
Main point of interaction fromusers
Bound to the controller for dataand events
Often works with a templateengine
Router
Responds to URL changes viaJavaScript
Changes between variousviews
Browser initiated routesType in a URLHyperlink
Client initiated routes
Change from one page or aview to another
Utilizes hash fragments
http://myurl.com/#/products/
JS rights to modify page URLAnything after '#' is fair game
Just like the anchor tag
Examples
Wild SPA AppsGmailFacebokTwitterTrelloAsana
Popular MV*Frameworks
BackboneAngularKendo UIEmberDurandalMeteor
Today's FocusBackboneAngularKendo UI
Backbone
Light-weight library
The basic foundation
Not a ton of extra frills
Heavy lifting is up to you
Huge community for tooling
Offers a set of helpful classes
Each one can- and will be -extended
Backbone main classesModelCollectionViewRouter
Model
Deals with all of our data
Bound to a view
Syncs back to our server
Backbone.Modelvar myModel = new Backbone.Model({});
Extend Methodvar Character = Backbone.Model.extend({ defaults: { name: 'Blanks', species: 'Human', description: 'No description yet.' }, initialize: function() { console.log('New character created'); }});
var jake = new Character({ name: 'Jake the Dog', species: 'Dog', description: 'A magical dog. Best friend, and brother, with Finn.'});
Use get() or set() to changedata
var finn = new Character({ name: 'Finn the Human' });
finn.set({ species: 'Human' });
var name = finn.get('name'); //Finn the Human
Collections
Group related models together
Methods for adding/removingmodels
Simple array-like object
Backbone.Collectionvar Character = Backbone.Model.extend({ defaults: { name: 'Blanks', species: 'Human', description: 'No description yet.' }, initialize: function() { console.log('New character created'); }});
var Cast = Backbone.Collection.extend({ model: Character});
var jake = new Character({ name: 'Jake the Dog', species: 'Dog', description: 'A magical dog. Best friend, and brother, with Finn.'});
var finn = new Character({ name: 'Finn the Human', species: 'Human', description: 'The last human in the Land of Ooo. Hangs out with Jake.'});
var castList = new Cast([ jake, finn ]);
console.log(castList.models);
View
The link between models andthe UI
Renders the models and theirdata
Views are bound to models orcollections
Receives events from theModel and HTML document
The 'el' propertyEvery view has an 'el' propertyIf not defined, a blank div is createdReferences the view's DOM objectPass in a HTML element to modify itCan be a jQuery object via $el
Backbone.Viewvar FinnView = Backbone.View.extend({ tagName: 'div', id: 'finnDiv', className: 'finnClass', attributes: { 'data-custom': 12345 }});
var quickView = new FinnView();
$('#placeholder').prepend(quickView.el);
Resulting HTML<div data-custom="12345" id="sampleDiv" class="sampleClass"></div>
Default templates byUnderscorejsBin.com/IWewESE/8/
Router
Use of hash fragments
http://myurl.com/#/characters/
Parses URL and findsappropriate function
Uses HTML5 History API ifpossible
Backbone.Routervar SampleRouter = Backbone.Router.extend({ routes: { 'character/:name': 'character' //route pattern : handler name }, character: function(name) { //handler //... }});
BackboneSummary
Barebones tools to build ourapp
Emphasis on data and Models
Not a ton of tools for the View
.extend({}) everything
Backbone main classesModelCollectionViewRouter
Model deals with all of our data
A collection has multipleModels
View needs a ModelWorks with Model and DOM
Router works with URL to servecorrect View
Angular
Created by Google
Believes HTML can be morepowerful
Extends HTML vocabulary
Tries to follow a pure HTMLpath
Angular componentsExpressionsControllersDirectivesRouting
Expressions
Allows us to bring data to theview
Uses a simple syntax{{ model.FieldName }}
One-way binding<div ng-controller="SampleController"> <span>{{ character.name }}</span></div>
Two-way binding<select ng-model="selectedCharacter"> <option value="0">Finn</option> <option value="1">Jake</option> <option value="2">BMO</option></select>
Controllers
Central component of Angularapps
Contains data, logic, and states
Creates a scope for the HTMLelement
$scope variable
Sample Controllervar sampleAppControllers = angular.module('sampleAppControllers', []);
sampleAppControllers.controller('ShowController', ['$scope', function ShowController($scope) { $scope.sampleVariable = 1; $scope.sampleArray = [{ fieldOne: 0, fieldTwo: "Test" }, { fieldOne: 1, fieldTwo: "Sample" }] $scope.sampleFunction: function() { //Function logic } }]);
$scope only available within theHTML element it is defined in
Directives
HTML-like attributes
Declared in view code
Helps with setting upAngular AppControllers and bindingAttributesConditional displayEvents
Sample Directivesng-app="appName"ng-controller="SampleCtrl"ng-model="ScopeVar"ng-src="{{scopeUrlVar}}"ng-click="eventHandler()"
Routing
Works with URL like you'd think
Single main viewPlaceholder element for content
Load other views via partialsJust HTML pages
Simple structure for routingvar sampleApp = angular.module('sampleApp', [ 'ngRoute', 'myControllers']);;
sampleApp.config(['$routeProvider', function($routeProvider) { $routeProvider.when('/test', { templateUrl: 'partials/test.html', controller: $routeProvider.when('/sample:id', { templateUrl: 'partials/sample.html', $routeProvider.otherwise({ redirectTo: '/' }); }]);
AngularSummary
Extension of HTML
Empowering your regular HTMLcode
Controllers rule all
Data can be bound one- or two-way
DOM manipulation viacontroller
Drop that jQuery ;)
Directives are extremely helpfulWire upp events and such
Routers use partials of HTML
Kendo UI
Part of Kendo UI Web
Combine SPA and MVVMFrameworks
Additional helpful itemsTemplate engineEffects and animationsUI widgetsCharts and gauges
Tooling across all parts of yourSPA
Kendo UI key piecesObservableViewLayoutRouter
Observable
Part of the Kendo UI MVVMframework
All fields are observable
All changes will propogate
kendo.observablevar finnModel = kendo.observable({ name: 'Finn the Human', species: 'Human', description: 'The last human in the Land of Ooo. Hangs out with Jake.'});
Use get() or set() with fieldsvar finnModel = kendo.observable({ name: 'Finn the Human', species: 'Dog', description: 'The last human in the Land of Ooo. Hangs out with Jake.'});
finnModel.set('species', 'Human');
var species = finnModel.get('species'); //Human
View
Can be defined with simpleHTML string
Works with Kendo UI templates
Tie in with our observables tocreate data bound UI
kendo.View()var index = new kendo.View('<span>Adventure Time!</span>');
index.render('#placeholder');
Layout
Provides a layout for views toadhere to
MasterPages for you .NET folks
Easily display views in contentsection
Can also be nested
kendo.Layoutvar view = new Kendo.View('<span>Finn the Human</span>');
var layout = new kendo.Layout('<header>Header</header><div id="content"></div><footer>Footer</footer>');
layout.render($('#app'));
layout.showIn('#content', view);
Router
Responsible for applicationstate
Navigate between views
Use of hash fragments
http://myurl.com/#/characters/
Can programmatically navigate
Use with Layout to show newcontent
kendo.Router()var router = new kendo.Router();router.route('/', function () { layout.showIn('#content', homeView);});
router.route('/character', function () { layout.showIn('#content', characterView);});
$(function() { router.start(); //very important
router.navigate('/character');});
Kendo UISummary
Tools across the board
Classes for dealing with data
Helpful UI and View classes
Large set of UI widgets
Kendo UI SPA key itemsObservableViewLayoutRouter
The EndThanks for attending!
@carlbergenhem
github.com/bergenhem/talks