wordpress & backbone.js

14
WORDPRESS & BACKBONE.JS Andrew Duthie

Upload: andrew-duthie

Post on 08-Aug-2015

27 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: WordPress & Backbone.js

WORDPRESS & BACKBONE.JSAndrew Duthie

Page 2: WordPress & Backbone.js

BACKBONE.JS• A JavaScript model-view-controller

(MVC) framework

• Provides structure to otherwise messy JavaScript code organization

• Supports REST APIs out-of-the-box

Page 3: WordPress & Backbone.js

BACKBONE.JS - MODELS

• Describes a single entity type

• Usually maps to a REST API single entity endpoint

• Analogous to a single WordPress post object

Page 4: WordPress & Backbone.js

BACKBONE.JS - MODELS

wp.api.models.Post = Backbone.Model.extend( {idAttribute: 'ID',

urlRoot: '/wp-json/wp/v2/posts',

defaults: {ID: null,title: '',status: 'draft',type: 'post',author: new wp.api.models.User(),content: '',/* ... */

}} );

Page 5: WordPress & Backbone.js

BACKBONE.JS - COLLECTIONS

• Describes a group of entities

• Usually maps to a REST API entity listing endpoint

• Analogous to the WordPress loop

Page 6: WordPress & Backbone.js

BACKBONE.JS - COLLECTIONS

wp.api.collections.Posts = Backbone.Collection.extend( {url: '/wp-json/wp/v2/post',

model: wp.api.models.Post} );

Page 7: WordPress & Backbone.js

BACKBONE.JS - VIEWS

• Describes how to render content to the page

• Analogous to a WordPress template

Page 8: WordPress & Backbone.js

BACKBONE.JS - VIEWSvar PostView = Backbone.View.extend( {

template: _.template('<h1><%= title %></h1>' +'<%= content %>'

),

initialize: function() {this.model.on( 'change', this.render, this );

},

render: function() {var html = this.template( this.model.attributes );this.$el.html( html );

return this;}

} );

Page 9: WordPress & Backbone.js

BACKBONE.JS - ROUTER

• Specifies the logic to perform when particular URLs are visited

• Typically reserved for “single-page application” type applications

• Somewhat analogous to WordPress add_rewrite_rule

Page 10: WordPress & Backbone.js

BACKBONE.JS - ROUTER

var Router = Backbone.Router.extend( {routes: {

'posts/:id': 'detail'},

detail: function( id ) {var post = new wp.api.models.Post( { ID: id } ),

view;

post.fetch();

view = new PostView( { model: post } );view.render();view.$el.appendTo( document.body );

}} );

Page 11: WordPress & Backbone.js

USE CASES• Organizing your existing JavaScript

• Widgets

• Plugins

• Single-page web apps

• JavaScript themes

Page 12: WordPress & Backbone.js

WHY USE IT?• Bundled as a built-in script

• Easy to use with WordPress JSON API

• Small framework, so doesn’t impact load times and is approachable to developers

Page 13: WordPress & Backbone.js

USING BACKBONE.JS

<?php

function mytheme_enqueue_backbone() { wp_enqueue_script( 'backbone' );}add_action( 'wp_enqueue_scripts', ‘mytheme_enqueue_backbone' );

Page 14: WordPress & Backbone.js

DEMOgithub.com/aduth/wordcamp-popular-movies