<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[2197] 2013/rmccue/trunk: First pass at Backbone models/collections</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://gsoc.trac.wordpress.org/changeset/2197">2197</a></dd>
<dt>Author</dt> <dd>rmccue</dd>
<dt>Date</dt> <dd>2013-08-07 04:23:16 +0000 (Wed, 07 Aug 2013)</dd>
</dl>

<h3>Log Message</h3>
<pre>First pass at Backbone models/collections

This will need to be updated as more entities are added in the coming weeks.

See <a href="http://gsoc.trac.wordpress.org/ticket/270">#270</a></pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#2013rmccuetrunkpluginphp">2013/rmccue/trunk/plugin.php</a></li>
</ul>

<h3>Added Paths</h3>
<ul>
<li><a href="#2013rmccuetrunkwpapijs">2013/rmccue/trunk/wp-api.js</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="2013rmccuetrunkpluginphp"></a>
<div class="modfile"><h4>Modified: 2013/rmccue/trunk/plugin.php (2196 => 2197)</h4>
<pre class="diff"><span>
<span class="info">--- 2013/rmccue/trunk/plugin.php     2013-08-07 04:15:55 UTC (rev 2196)
+++ 2013/rmccue/trunk/plugin.php        2013-08-07 04:23:16 UTC (rev 2197)
</span><span class="lines">@@ -75,6 +75,15 @@
</span><span class="cx"> register_deactivation_hook( __FILE__, 'json_api_activation' );
</span><span class="cx"> 
</span><span class="cx"> /**
</span><ins>+ * Register our API Javascript helpers
+ */
+function json_register_scripts() {
+       wp_register_script( 'wp-api', plugins_url( dirname( __FILE__ ) . '/wp-api.js' ), array( 'jquery', 'backbone', 'underscore' ), '0.4-dev', true );
+       wp_localize_script( 'wp-api', 'wpApiOptions', array( 'base' => json_url() ) );
+}
+add_action( 'wp_enqueue_scripts', 'json_register_scripts', -100 );
+
+/**
</ins><span class="cx">  * Get URL to a JSON endpoint on a site
</span><span class="cx">  *
</span><span class="cx">  * @todo Check if this is even necessary
</span></span></pre></div>
<a id="2013rmccuetrunkwpapijs"></a>
<div class="addfile"><h4>Added: 2013/rmccue/trunk/wp-api.js (0 => 2197)</h4>
<pre class="diff"><span>
<span class="info">--- 2013/rmccue/trunk/wp-api.js                              (rev 0)
+++ 2013/rmccue/trunk/wp-api.js 2013-08-07 04:23:16 UTC (rev 2197)
</span><span class="lines">@@ -0,0 +1,229 @@
</span><ins>+(function ($) {
+       window.wp = window.wp || {};
+       var api = wp.api = wp.api || {};
+
+       // Date parsing code
+       // From: https://github.com/csnover/js-iso8601
+       // Copyright 2011 Colin Snover, MIT Licensed
+       var origParse = Date.parse, numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ];
+       api.parseISO8601 = function (date) {
+               var timestamp, struct, minutesOffset = 0;
+
+               // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string
+               // before falling back to any implementation-specific date parsing, so that’s what we do, even if native
+               // implementations could be faster
+               //              1 YYYY                2 MM       3 DD           4 HH    5 mm       6 ss        7 msec        8 Z 9 ±    10 tzHH    11 tzmm
+               if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) {
+                       // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC
+                       for (var i = 0, k; (k = numericKeys[i]); ++i) {
+                               struct[k] = +struct[k] || 0;
+                       }
+
+                       // allow undefined days and months
+                       struct[2] = (+struct[2] || 1) - 1;
+                       struct[3] = +struct[3] || 1;
+
+                       if (struct[8] !== 'Z' && struct[9] !== undefined) {
+                               minutesOffset = struct[10] * 60 + struct[11];
+
+                               if (struct[9] === '+') {
+                                       minutesOffset = 0 - minutesOffset;
+                               }
+                       }
+
+                       timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]);
+               }
+               else {
+                       timestamp = origParse ? origParse(date) : NaN;
+               }
+
+               return timestamp;
+       };
+
+       // ECMAScript 5 shim, from MDN
+       // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
+       if ( !Date.prototype.toISOString ) {
+               var pad = function (number) {
+                       var r = String(number);
+                       if ( r.length === 1 ) {
+                               r = '0' + r;
+                       }
+                       return r;
+               };
+
+               Date.prototype.toISOString = function() {
+                       return this.getUTCFullYear()
+                               + '-' + pad( this.getUTCMonth() + 1 )
+                               + '-' + pad( this.getUTCDate() )
+                               + 'T' + pad( this.getUTCHours() )
+                               + ':' + pad( this.getUTCMinutes() )
+                               + ':' + pad( this.getUTCSeconds() )
+                               + '.' + String( (this.getUTCMilliseconds()/1000).toFixed(3) ).slice( 2, 5 )
+                               + 'Z';
+               };
+       }
+
+       // Set the root URL from the global variable, if available
+       api.root = "";
+       if (wpApiOptions) {
+               api.root = wpApiOptions.base;
+       }
+
+       /**
+        * wp.api.models
+        *
+        * Model container
+        */
+       api.models = {};
+
+       /**
+        * wp.api.models.User
+        *
+        * User Entity model
+        */
+       api.models.User = Backbone.Model.extend({
+               urlRoot: api.root + "/users",
+
+               defaults: {
+                       ID: 0,
+                       name: "",
+                       slug: "",
+                       URL: "",
+                       avatar: "",
+                       meta: {
+                               links: {}
+                       }
+               },
+
+               avatar: function (size) {
+                       return this.get('avatar') + '&s=' + size;
+               }
+       });
+
+       var parseable_dates = [ 'date', 'date_gmt', 'modified', 'modified_gmt' ];
+
+       /**
+        * wp.api.models.Post
+        *
+        * Post Entity model
+        */
+       api.models.Post = Backbone.Model.extend({
+               // Technically, these are probably not needed
+               defaults: function () {
+                       return {
+                               ID:             0,
+                               title:          "",
+                               status:         "draft",
+                               type:           "post",
+                               author:         new api.models.User(),
+                               content:        "",
+                               parent:         0,
+                               link:           "",
+                               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",
+                               terms:          {},
+                               post_meta:      {},
+                               meta: {
+                                       links: {}
+                               }
+                       };
+               },
+
+               idAttribute: "ID",
+
+               urlRoot: api.root + "/posts",
+
+               /**
+                * Serialize the entity
+                *
+                * Overriden for correct date handling
+                * @return {!Object} Serializable attributes
+                */
+               toJSON: function () {
+                       var attributes = this.attributes;
+
+                       // Serialize Date objects back into 8601 strings
+                       _.each( parseable_dates, function ( key ) {
+                               attributes[ key ] = attributes[ key ].toISOString();
+                       });
+
+                       return attributes;
+               },
+
+               /**
+                * Unserialize the entity
+                *
+                * Overriden for correct date handling
+                * @param {!Object} response Attributes parsed from JSON
+                * @param {!Object} options Request options
+                * @return {!Object} Fully parsed attributes
+                */
+               parse: function ( response, options ) {
+                       console.log(response);
+
+                       // Parse dates into native Date objects
+                       _.each( parseable_dates, function ( key ) {
+                               response[ key ] = api.parseISO8601( response[ key ] );
+                       });
+                       return response;
+               },
+
+               /**
+                * Get parent post
+                *
+                * @return {wp.api.models.Post} Parent post, null if not found
+                */
+               parent: function () {
+                       var parent = this.get('parent');
+
+                       // Return null if we don't have a parent
+                       if (parent === 0) {
+                               return null;
+                       }
+
+                       // Can we get this from its collection?
+                       if (this.collection) {
+                               return this.collection.get(parent);
+                       }
+                       else {
+                               // Otherwise, get the post directly
+                               var post = new api.models.Post({
+                                       id: parent
+                               });
+
+                               // Note that this acts asynchronously
+                               api.models.post.fetch();
+                               return post;
+                       }
+               }
+       });
+
+       /**
+        * wp.api.collections
+        */
+       api.collections = {};
+
+       /**
+        * wp.api.collections.Posts
+        */
+       api.collections.Posts = Backbone.Collection.extend({
+               url: api.root + "/posts",
+
+               model: api.models.Post
+       });
+
+       var post = new api.models.Post({ID: 1});
+       post.fetch();
+})(jQuery);
</ins><span class="cx">\ No newline at end of file
</span><span class="cx">Property changes on: 2013/rmccue/trunk/wp-api.js
</span><span class="cx">___________________________________________________________________
</span></span></pre></div>
<a id="svnexecutable"></a>
<div class="addfile"><h4>Added: svn:executable</h4></div>
<ins>+*
</ins><span class="cx">\ No newline at end of property
</span></div>

</body>
</html>