SlideShare a Scribd company logo
1 of 50
Download to read offline
WORDPRESS AS THE 
BACKBONE(.JS)
https://github.com/beaulebens/WROPE 
! 
@beaulebens 
! 
#wctoga
BEAU LEBENS 
AUTOMATTIC 
O2
WORDPRESS IS FOR BLOGS
WORDPRESS IS FOR WEBSITES
WORDPRESS IS A CMS
WORDPRESS IS A 
PUBLISHING PLATFORM
WORDPRESS IS AN 
APPLICATION BACKEND
WORDPRESS.COM REST API 
https://developer.wordpress.com/
JSON REST API 
https://wordpress.org/plugins/json-rest-api/
JSON
JavaScript 
Object 
Notation
REST
REpresentational 
State 
Transfer
POST (create) 
GET (read) 
PUT (update) 
DELETE (delete)
http://example.com/wp-json/posts/123/comments
API
Application 
Programming 
Interface
API JSON 
“Programmatic access to 
your content in a universal format 
via simple HTTP requests” 
REST
• Read and Write (when authenticated) 
• Perform “all” operations 
• Any system that talks HTTP + JSON
LET’S BUILD AN APP! 
• Mobile first, obvs 
• Lightweight/lean (mobile is slow) 
• The web is cool, so we’ll use web technologies 
• Developer with no WordPress/PHP experience
WROPE 
WordPress 
River 
Of 
Posts 
Experiment
JAVASCRIPT?
BACKBONE.JS 
• Helps write structured and sane client-side web apps 
• Relatively unopinionated/non-prescriptive 
• Basic building blocks for better web apps 
• Packages Underscore.js for great helper utilities 
• Bundled with WP core 
• Small (6.5kb! But that’s a bit deceptive, as we’ll see) 
• Lots of boilerplate (but very customizable)
https://github.com/WP-API/client-js
ROUTES 
routerObj: Backbone.Router.extend({ 
root: '/dev/WROPE/', ! 
routes: { 
'': 'index', 
‘posts/:post’: 'post' 
}, ! 
index: function() { 
// Get a collection of posts from WP and render them once returned 
WROPE.fetchPosts( function() { this.renderRiver(); }.bind( this ) ); 
}, ! 
renderRiver: function() { 
WROPE.postsRiver = new WROPE.postsView( { collection: WROPE.posts } ); ! 
// Load optimized inline images, and reload them when the page is resized 
WROPE.optimizeImageSize(); 
$(window).on('resize', _.debounce( WROPE.optimizeImageSize, 500 ) ); 
}, ! 
post: function( post ) { 
if ( null === WROPE.posts ) { 
WROPE.fetchPosts( function() { this.renderPost( post ); }.bind( this ) ); 
} else { 
this.renderPost( post ); 
} 
}, ! 
renderPost: function( post ) { 
var thePost = WROPE.posts.get( post ); 
var postView = new WROPE.postView( { model: thePost, tagName: 'div' } ); 
$( '#wrope' ).slideUp( function() { 
$(this).html( postView.$el ).slideDown(); 
WROPE.optimizeImageSize(); 
}); 
return; 
} 
}), 
Application state via URIs
• Keep track of where you are in your 
application 
• Allow for history management (Back button!) 
• Can use pushState or hash-based URIs 
• Fire events on matched routes 
• Fire callbacks based on their matched routes
MODELS 
/** 
* Backbone model for single posts 
*/ 
wp.api.models.Post = BaseModel.extend( _.extend( 
/** @lends Post.prototype */ 
{ 
idAttribute: 'ID', ! 
urlRoot: WP_API_Settings.root + '/posts', ! 
defaults: { 
ID: null, 
title: '', 
status: 'draft', 
type: 'post', 
author: new wp.api.models.User(), 
content: '', 
link: '', 
'parent': 0, 
date: new Date(), 
date_gmt: new Date(), 
modified: new Date(), 
modified_gmt: new Date(), 
format: 'standard', 
slug: '', 
guid: '', 
excerpt: '', 
menu_order: 0, 
comment_status: 'open', 
ping_status: 'open', 
sticky: false, 
date_tz: 'Etc/UTC', 
modified_tz: 'Etc/UTC', 
featured_image: null, 
terms: {}, 
post_meta: {}, 
meta: { 
links: {} 
} 
} 
}, TimeStampedMixin, HierarchicalMixin ) 
); 
Structured key-value data stores (Post, Comment, etc)
• Fire events when something changes 
• Keep track of changed values internally 
• Backed up by a REST API/endpoint (server 
magic!) 
• Have functions for converting to/from the 
expected model properties
COLLECTIONS 
/** 
* Backbone collection for posts 
*/ 
wp.api.collections.Posts = BaseCollection.extend( 
/** @lends Posts.prototype */ 
{ 
url: WP_API_Settings.root + '/posts', 
List of models (Posts, Comments, etc) 
! 
model: wp.api.models.Post 
} 
);
• Bubble up model events 
• Fire their own events (add, remove, reset) 
• Have a ‘comparator’ to dynamically decide sort 
order 
• Have functions for filtering/retrieving specific 
models 
• Backed up by a REST API/endpoint
VIEWS 
postView: Backbone.View.extend({ 
tagName: 'li', 
! 
className: 'post', 
! 
template: _.template( $('#tpl-post').text() ), 
! 
events: { 
'click a': 'preventDefault', 
'click h1.post-title a': 'goToPage', 
'click .featured-image a': 'goToPage' 
}, 
! 
initialize: function( options ) { 
this.render(); 
}, 
! 
preventDefault: function( e ) { 
e.preventDefault(); 
}, 
! 
goToPage: function() { 
WROPE.router.navigate( '/' + this.model.get( 'ID' ), { trigger: true } ); 
return; 
}, 
! 
render: function() { 
this.$el.html( this.template( this.model.attributes ) ); 
return this; 
} 
}), 
Visual representation of models/collections
• Listen to events (on models/collections) and 
update appropriately 
• Handles interactions with the View (clicks etc) 
• Correspond to a DOM element (even if it’s 
not inserted into the page yet) 
• Are agnostic to your templating strategy
SPEAKING OF TEMPLATES 
<script type="text/html" id="tpl-post"> 
<div class="post-header"> 
<div class="post-avatar"><img src="<%= author.attributes.avatar %>" width="40" height="40"></div> 
<h1 class="post-title"><a href="<%= link %>"><%= title %></a></h1> 
<div class="post-author"><%= author.name %></div> 
<div class="post-date"><%= date %></div> 
</div> 
<div class="post-body"> 
<% if ( featured_image ) { %> 
<div class="featured-image"> 
<a href="<%= link %>"> 
<img data-src="<%= photon( featured_image.source ) %>" alt="" class="feature"> 
</a> 
</div> 
<% } %> 
<%= excerpt %> 
</div> 
</script> 
HTML templates, delivered in the DOM as script tags
• Built-in ERB-style in Underscore.js 
• Token-based replacements (with escaping) 
• Basic logic 
• Handlebars.js, Mustache.js, etc are also 
supported
SIDELINE
Routes 
Models 
Collections 
Views/Templates
One more thing…
<?php 
! 
// One off hack to allow Cross Origin Resource Sharing from my laptop 
add_action( 'wp_json_server_before_serve', function() { 
// Allow my laptop to talk to WordPress 
header( 'Access-Control-Allow-Origin: http://beaurrito.local' ); 
! 
// jQuery sends a preflight OPTIONS request to confirm control headers. 
// If that's what this request is, then after we've sent the above headers we can bail. 
if ( 'OPTIONS' == strtoupper( $_SERVER['REQUEST_METHOD'] ) ) { 
exit; 
} 
}); 
CORS HACK 
On your WP install (mu-plugins)
CODE + DEMO
https://github.com/beaulebens/WROPE 
! 
Beau Lebens 
@beaulebens 
http://dntd.cc/

More Related Content

What's hot

The New UI - Staying Strong with Flexbox, SASS, and {{Mustache.js}}
The New UI - Staying Strong with Flexbox, SASS, and {{Mustache.js}}The New UI - Staying Strong with Flexbox, SASS, and {{Mustache.js}}
The New UI - Staying Strong with Flexbox, SASS, and {{Mustache.js}}Eric Carlisle
 
HTML5 Web Workers-unleashed
HTML5 Web Workers-unleashedHTML5 Web Workers-unleashed
HTML5 Web Workers-unleashedPeter Lubbers
 
Once upon a time, there were css, js and server-side rendering
Once upon a time, there were css, js and server-side renderingOnce upon a time, there were css, js and server-side rendering
Once upon a time, there were css, js and server-side renderingAndrea Giannantonio
 
Single Page Apps with Drupal 8
Single Page Apps with Drupal 8Single Page Apps with Drupal 8
Single Page Apps with Drupal 8Chris Tankersley
 
Drupal and diversity of Single sign-on systems
Drupal and diversity of Single sign-on systemsDrupal and diversity of Single sign-on systems
Drupal and diversity of Single sign-on systemsAlex S
 
Enjoy the vue.js
Enjoy the vue.jsEnjoy the vue.js
Enjoy the vue.jsTechExeter
 
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...andrewnacin
 
Integrating Browserify with Sprockets
Integrating Browserify with SprocketsIntegrating Browserify with Sprockets
Integrating Browserify with SprocketsSpike Brehm
 
Getting Started with HTML 5 Web workers
Getting Started with HTML 5 Web workersGetting Started with HTML 5 Web workers
Getting Started with HTML 5 Web workersFlumes
 
WordPress Structure and Best Practices
WordPress Structure and Best PracticesWordPress Structure and Best Practices
WordPress Structure and Best Practicesmarkparolisi
 
A modern front end development workflow for Magnolia at Atlassian
A modern front end development workflow for Magnolia at AtlassianA modern front end development workflow for Magnolia at Atlassian
A modern front end development workflow for Magnolia at AtlassianMagnolia
 
Hash Signaling Made Easy
Hash Signaling Made EasyHash Signaling Made Easy
Hash Signaling Made Easydavidgouldin
 
Don't Over-React - just use Vue!
Don't Over-React - just use Vue!Don't Over-React - just use Vue!
Don't Over-React - just use Vue!Raymond Camden
 
I use drupal / 我是 OO 師,我用 Drupal
I use drupal / 我是 OO 師,我用 DrupalI use drupal / 我是 OO 師,我用 Drupal
I use drupal / 我是 OO 師,我用 DrupalChris Wu
 
Build a Better Editing Experience with Advanced Custom Fields
Build a Better Editing Experience with Advanced Custom FieldsBuild a Better Editing Experience with Advanced Custom Fields
Build a Better Editing Experience with Advanced Custom FieldsJeseph Meyers
 
Take your drupal sites offline
Take your drupal sites offlineTake your drupal sites offline
Take your drupal sites offlineChris Ward
 
The Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.jsThe Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.jsHolly Schinsky
 
DrupalGap. How to create native application for mobile devices based on Drupa...
DrupalGap. How to create native application for mobile devices based on Drupa...DrupalGap. How to create native application for mobile devices based on Drupa...
DrupalGap. How to create native application for mobile devices based on Drupa...DrupalCampDN
 

What's hot (20)

The New UI - Staying Strong with Flexbox, SASS, and {{Mustache.js}}
The New UI - Staying Strong with Flexbox, SASS, and {{Mustache.js}}The New UI - Staying Strong with Flexbox, SASS, and {{Mustache.js}}
The New UI - Staying Strong with Flexbox, SASS, and {{Mustache.js}}
 
HTML5 Web Workers-unleashed
HTML5 Web Workers-unleashedHTML5 Web Workers-unleashed
HTML5 Web Workers-unleashed
 
Once upon a time, there were css, js and server-side rendering
Once upon a time, there were css, js and server-side renderingOnce upon a time, there were css, js and server-side rendering
Once upon a time, there were css, js and server-side rendering
 
Single Page Apps with Drupal 8
Single Page Apps with Drupal 8Single Page Apps with Drupal 8
Single Page Apps with Drupal 8
 
Drupal and diversity of Single sign-on systems
Drupal and diversity of Single sign-on systemsDrupal and diversity of Single sign-on systems
Drupal and diversity of Single sign-on systems
 
Intro to Sails.js
Intro to Sails.jsIntro to Sails.js
Intro to Sails.js
 
Enjoy the vue.js
Enjoy the vue.jsEnjoy the vue.js
Enjoy the vue.js
 
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
 
Integrating Browserify with Sprockets
Integrating Browserify with SprocketsIntegrating Browserify with Sprockets
Integrating Browserify with Sprockets
 
Getting Started with HTML 5 Web workers
Getting Started with HTML 5 Web workersGetting Started with HTML 5 Web workers
Getting Started with HTML 5 Web workers
 
WordPress Structure and Best Practices
WordPress Structure and Best PracticesWordPress Structure and Best Practices
WordPress Structure and Best Practices
 
A modern front end development workflow for Magnolia at Atlassian
A modern front end development workflow for Magnolia at AtlassianA modern front end development workflow for Magnolia at Atlassian
A modern front end development workflow for Magnolia at Atlassian
 
Hash Signaling Made Easy
Hash Signaling Made EasyHash Signaling Made Easy
Hash Signaling Made Easy
 
Drupal8 + AngularJS
Drupal8 + AngularJSDrupal8 + AngularJS
Drupal8 + AngularJS
 
Don't Over-React - just use Vue!
Don't Over-React - just use Vue!Don't Over-React - just use Vue!
Don't Over-React - just use Vue!
 
I use drupal / 我是 OO 師,我用 Drupal
I use drupal / 我是 OO 師,我用 DrupalI use drupal / 我是 OO 師,我用 Drupal
I use drupal / 我是 OO 師,我用 Drupal
 
Build a Better Editing Experience with Advanced Custom Fields
Build a Better Editing Experience with Advanced Custom FieldsBuild a Better Editing Experience with Advanced Custom Fields
Build a Better Editing Experience with Advanced Custom Fields
 
Take your drupal sites offline
Take your drupal sites offlineTake your drupal sites offline
Take your drupal sites offline
 
The Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.jsThe Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.js
 
DrupalGap. How to create native application for mobile devices based on Drupa...
DrupalGap. How to create native application for mobile devices based on Drupa...DrupalGap. How to create native application for mobile devices based on Drupa...
DrupalGap. How to create native application for mobile devices based on Drupa...
 

Similar to Build a WordPress mobile app with Backbone.js

Introduction to backbone presentation
Introduction to backbone presentationIntroduction to backbone presentation
Introduction to backbone presentationBrian Hogg
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAERon Reiter
 
Single Page Applications on JavaScript and ASP.NET MVC4
Single Page Applications on JavaScript and ASP.NET MVC4Single Page Applications on JavaScript and ASP.NET MVC4
Single Page Applications on JavaScript and ASP.NET MVC4Yuriy Shapovalov
 
Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stackPaul Bearne
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksHjörtur Hilmarsson
 
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...mfrancis
 
OSGi and Spring Data for simple (Web) Application Development
OSGi and Spring Data  for simple (Web) Application DevelopmentOSGi and Spring Data  for simple (Web) Application Development
OSGi and Spring Data for simple (Web) Application DevelopmentChristian Baranowski
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's CodeWildan Maulana
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Refresh Austin - Intro to Dexy
Refresh Austin - Intro to DexyRefresh Austin - Intro to Dexy
Refresh Austin - Intro to Dexyananelson
 
Introduction to Plugin Programming, WordCamp Miami 2011
Introduction to Plugin Programming, WordCamp Miami 2011Introduction to Plugin Programming, WordCamp Miami 2011
Introduction to Plugin Programming, WordCamp Miami 2011David Carr
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Djangofool2nd
 
Styling components with JavaScript
Styling components with JavaScriptStyling components with JavaScript
Styling components with JavaScriptbensmithett
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to TornadoGavin Roy
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCpootsbook
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)Igor Bronovskyy
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Eric Palakovich Carr
 
Primefaces Nextgen Lju
Primefaces Nextgen LjuPrimefaces Nextgen Lju
Primefaces Nextgen LjuSkills Matter
 

Similar to Build a WordPress mobile app with Backbone.js (20)

Introduction to backbone presentation
Introduction to backbone presentationIntroduction to backbone presentation
Introduction to backbone presentation
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
 
Single Page Applications on JavaScript and ASP.NET MVC4
Single Page Applications on JavaScript and ASP.NET MVC4Single Page Applications on JavaScript and ASP.NET MVC4
Single Page Applications on JavaScript and ASP.NET MVC4
 
Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stack
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
 
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
 
OSGi and Spring Data for simple (Web) Application Development
OSGi and Spring Data  for simple (Web) Application DevelopmentOSGi and Spring Data  for simple (Web) Application Development
OSGi and Spring Data for simple (Web) Application Development
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
Html5 For Jjugccc2009fall
Html5 For Jjugccc2009fallHtml5 For Jjugccc2009fall
Html5 For Jjugccc2009fall
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Refresh Austin - Intro to Dexy
Refresh Austin - Intro to DexyRefresh Austin - Intro to Dexy
Refresh Austin - Intro to Dexy
 
Introduction to Plugin Programming, WordCamp Miami 2011
Introduction to Plugin Programming, WordCamp Miami 2011Introduction to Plugin Programming, WordCamp Miami 2011
Introduction to Plugin Programming, WordCamp Miami 2011
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Django
 
Styling components with JavaScript
Styling components with JavaScriptStyling components with JavaScript
Styling components with JavaScript
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
Primefaces Nextgen Lju
Primefaces Nextgen LjuPrimefaces Nextgen Lju
Primefaces Nextgen Lju
 

Recently uploaded

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 

Recently uploaded (20)

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 

Build a WordPress mobile app with Backbone.js

  • 1. WORDPRESS AS THE BACKBONE(.JS)
  • 5.
  • 6. WORDPRESS IS FOR WEBSITES
  • 7.
  • 9.
  • 10. WORDPRESS IS A PUBLISHING PLATFORM
  • 11.
  • 12. WORDPRESS IS AN APPLICATION BACKEND
  • 13.
  • 14.
  • 15. WORDPRESS.COM REST API https://developer.wordpress.com/
  • 16. JSON REST API https://wordpress.org/plugins/json-rest-api/
  • 17. JSON
  • 19. REST
  • 21. POST (create) GET (read) PUT (update) DELETE (delete)
  • 23. API
  • 25. API JSON “Programmatic access to your content in a universal format via simple HTTP requests” REST
  • 26. • Read and Write (when authenticated) • Perform “all” operations • Any system that talks HTTP + JSON
  • 27. LET’S BUILD AN APP! • Mobile first, obvs • Lightweight/lean (mobile is slow) • The web is cool, so we’ll use web technologies • Developer with no WordPress/PHP experience
  • 28. WROPE WordPress River Of Posts Experiment
  • 29.
  • 31.
  • 32. BACKBONE.JS • Helps write structured and sane client-side web apps • Relatively unopinionated/non-prescriptive • Basic building blocks for better web apps • Packages Underscore.js for great helper utilities • Bundled with WP core • Small (6.5kb! But that’s a bit deceptive, as we’ll see) • Lots of boilerplate (but very customizable)
  • 34. ROUTES routerObj: Backbone.Router.extend({ root: '/dev/WROPE/', ! routes: { '': 'index', ‘posts/:post’: 'post' }, ! index: function() { // Get a collection of posts from WP and render them once returned WROPE.fetchPosts( function() { this.renderRiver(); }.bind( this ) ); }, ! renderRiver: function() { WROPE.postsRiver = new WROPE.postsView( { collection: WROPE.posts } ); ! // Load optimized inline images, and reload them when the page is resized WROPE.optimizeImageSize(); $(window).on('resize', _.debounce( WROPE.optimizeImageSize, 500 ) ); }, ! post: function( post ) { if ( null === WROPE.posts ) { WROPE.fetchPosts( function() { this.renderPost( post ); }.bind( this ) ); } else { this.renderPost( post ); } }, ! renderPost: function( post ) { var thePost = WROPE.posts.get( post ); var postView = new WROPE.postView( { model: thePost, tagName: 'div' } ); $( '#wrope' ).slideUp( function() { $(this).html( postView.$el ).slideDown(); WROPE.optimizeImageSize(); }); return; } }), Application state via URIs
  • 35. • Keep track of where you are in your application • Allow for history management (Back button!) • Can use pushState or hash-based URIs • Fire events on matched routes • Fire callbacks based on their matched routes
  • 36. MODELS /** * Backbone model for single posts */ wp.api.models.Post = BaseModel.extend( _.extend( /** @lends Post.prototype */ { idAttribute: 'ID', ! urlRoot: WP_API_Settings.root + '/posts', ! defaults: { ID: null, title: '', status: 'draft', type: 'post', author: new wp.api.models.User(), content: '', link: '', 'parent': 0, date: new Date(), date_gmt: new Date(), modified: new Date(), modified_gmt: new Date(), format: 'standard', slug: '', guid: '', excerpt: '', menu_order: 0, comment_status: 'open', ping_status: 'open', sticky: false, date_tz: 'Etc/UTC', modified_tz: 'Etc/UTC', featured_image: null, terms: {}, post_meta: {}, meta: { links: {} } } }, TimeStampedMixin, HierarchicalMixin ) ); Structured key-value data stores (Post, Comment, etc)
  • 37. • Fire events when something changes • Keep track of changed values internally • Backed up by a REST API/endpoint (server magic!) • Have functions for converting to/from the expected model properties
  • 38. COLLECTIONS /** * Backbone collection for posts */ wp.api.collections.Posts = BaseCollection.extend( /** @lends Posts.prototype */ { url: WP_API_Settings.root + '/posts', List of models (Posts, Comments, etc) ! model: wp.api.models.Post } );
  • 39. • Bubble up model events • Fire their own events (add, remove, reset) • Have a ‘comparator’ to dynamically decide sort order • Have functions for filtering/retrieving specific models • Backed up by a REST API/endpoint
  • 40. VIEWS postView: Backbone.View.extend({ tagName: 'li', ! className: 'post', ! template: _.template( $('#tpl-post').text() ), ! events: { 'click a': 'preventDefault', 'click h1.post-title a': 'goToPage', 'click .featured-image a': 'goToPage' }, ! initialize: function( options ) { this.render(); }, ! preventDefault: function( e ) { e.preventDefault(); }, ! goToPage: function() { WROPE.router.navigate( '/' + this.model.get( 'ID' ), { trigger: true } ); return; }, ! render: function() { this.$el.html( this.template( this.model.attributes ) ); return this; } }), Visual representation of models/collections
  • 41. • Listen to events (on models/collections) and update appropriately • Handles interactions with the View (clicks etc) • Correspond to a DOM element (even if it’s not inserted into the page yet) • Are agnostic to your templating strategy
  • 42. SPEAKING OF TEMPLATES <script type="text/html" id="tpl-post"> <div class="post-header"> <div class="post-avatar"><img src="<%= author.attributes.avatar %>" width="40" height="40"></div> <h1 class="post-title"><a href="<%= link %>"><%= title %></a></h1> <div class="post-author"><%= author.name %></div> <div class="post-date"><%= date %></div> </div> <div class="post-body"> <% if ( featured_image ) { %> <div class="featured-image"> <a href="<%= link %>"> <img data-src="<%= photon( featured_image.source ) %>" alt="" class="feature"> </a> </div> <% } %> <%= excerpt %> </div> </script> HTML templates, delivered in the DOM as script tags
  • 43. • Built-in ERB-style in Underscore.js • Token-based replacements (with escaping) • Basic logic • Handlebars.js, Mustache.js, etc are also supported
  • 45.
  • 46. Routes Models Collections Views/Templates
  • 48. <?php ! // One off hack to allow Cross Origin Resource Sharing from my laptop add_action( 'wp_json_server_before_serve', function() { // Allow my laptop to talk to WordPress header( 'Access-Control-Allow-Origin: http://beaurrito.local' ); ! // jQuery sends a preflight OPTIONS request to confirm control headers. // If that's what this request is, then after we've sent the above headers we can bail. if ( 'OPTIONS' == strtoupper( $_SERVER['REQUEST_METHOD'] ) ) { exit; } }); CORS HACK On your WP install (mu-plugins)
  • 50. https://github.com/beaulebens/WROPE ! Beau Lebens @beaulebens http://dntd.cc/