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

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 

Recently uploaded (20)

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 

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/