Skip to content

Instantly share code, notes, and snippets.

@joshcarr
Forked from anonymous/fiddle.response.json
Last active December 10, 2015 08:38
Show Gist options
  • Save joshcarr/4409077 to your computer and use it in GitHub Desktop.
Save joshcarr/4409077 to your computer and use it in GitHub Desktop.
<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<h1>Backbone TEST</h1>
<div id="main"></div>
</body>
</html>
// =============================================
// = Backbone.LayoutManager configuration =
// =============================================
Backbone.LayoutManager.configure({
fetch: function(path) {
return JST[path];
},
render: function(template, context) {
return template(context);
},
manage: true
});
// Provide a global location to place configuration settings and module
// creation.
var app = {
// The root path to run the application through.
root: '/joshcarr/9f2UL/6/',
};
// Mix Backbone.Events, modules, and layout management into the app object.
_.extend(app, {
// Create a custom object with a nested Views object.
module: function(additionalProps) {
return _.extend({ Views: {} }, additionalProps);
},
// Helper for specific layouts.
useLayout: function(name) {
// If already using this Layout, then don't re-inject into the DOM.
if (this.layout && this.layout.options.template === name) {
return this.layout;
}
// If a layout already exists, remove it from the DOM.
if (this.layout) {
this.layout.remove();
}
// Create a new Layout.
var layout = new Backbone.Layout({
template: name,
className: 'layout ' + name,
id: 'layout'
});
// Insert into the DOM.
$('#main').empty().append(layout.el);
// Render the layout.
layout.render();
// Cache the reference on the Router.
this.layout = layout;
// Return the reference, for later usage.
return layout;
}
}, Backbone.Events);
// =============================================
// = Templates =
// =============================================
var JST = {};
JST['main'] = Handlebars.compile(
"<header id=\"header\"><h2>Our List of Things</h2></header><div id=\"books\"</div>");
JST['booklist'] = Handlebars.compile(
"<h3>Books</h3><ul id=\"book-list\"></ul>");
JST['booklistitem'] = Handlebars.compile(
"Book: {{name}}");
// =============================================
// = Book Module with Model, Collection, View =
// =============================================
var Book = app.module();
Book.Model = Backbone.Model.extend();
Book.Collection = Backbone.Collection.extend({
url: '/gh/get/response.json/4409077/',
parse: function(obj) {
console.log(obj);
return obj;
}
});
// = Item View =
Book.Views.Item = Backbone.View.extend({
template: 'booklistitem',
tagName: 'li',
events: {},
serialize: function() {
return { model: this.model };
},
cleanup: function() {
this.model.off(null, null, this);
},
initialize: function() {
this.model.on('change', this.render, this);
},
afterRender: function (argument) {
}
});
// = List View =
Book.Views.List = Backbone.View.extend({
template: 'booklist',
serialize: function() {
return { collection: this.collection };
},
beforeRender: function() {
this.collection.each(function( book ) {
this.insertView('ul', new Book.Views.Item({
model: book
}));
}, this);
},
afterRender: function() {
},
initialize: function() {
this.collection.on('reset', this.render, this);
this.collection.on('fetch', function() {
this.$('ul').parent().html('...loading...');
}, this);
}
});
// =============================================
// = Backbone Router Setup =
// =============================================
var Router = Backbone.Router.extend({
routes: {
'*path': 'books'
},
reset: function() {
// Reset collections and models to initial state.
if (this.books.length) {
this.books.reset();
}
},
initialize: function() {
var layout;
console.log('init');
// create a version of the function that can only be called one time
//mainSetup = _.once( common.main );
// Set up the collections and models.
this.books = new Book.Collection();
// Use main layout
layout = app.useLayout('main');
// set up the main layout methods after the layout renders
//layout.on('afterRender', function() {
// mainSetup();
//}, this);
},
books: function ( ) {
console.log('books!');
this.reset();
app.layout.setViews({
'#books': new Book.Views.List({
collection: this.books
})
}).render();
this.books.fetch();
}
});
// Define your master router on the application namespace and trigger all
// navigation from this instance.
app.router = new Router();
// =============================================
// = Starting the Backbone app =
// =============================================
// Trigger the initial route and enable HTML5 History API support, set the
// root folder to '/' by default. Change in app.js.
Backbone.history.start({ pushState: false, root: app.root });
// All navigation that is relative should be passed through the navigate
// method, to be processed by the router. If the link has a `data-bypass`
// attribute, bypass the delegation completely.
$(document).on('click', 'a:not([data-bypass])', function(evt) {
console.log('click');
// Get the absolute anchor href.
var href = { prop: $(this).prop('href'), attr: $(this).attr('href') };
// Get the absolute root.
var root = location.protocol + '//' + location.host + app.root;
// Ensure the root is part of the anchor href, meaning it's relative.
if (href.prop && href.prop.slice(0, root.length) === root) {
// Stop the default event to ensure the link will not cause a page
// refresh.
evt.preventDefault();
// `Backbone.history.navigate` is sufficient for all Routers and will
// trigger the correct events. The Router's internal `navigate` method
// calls this anyways. The fragment is sliced from the root.
Backbone.history.navigate(href.attr, true);
}
});
name: Request.HTML - jsFiddle/Gist integration demo
description: jsFiddle demo hosted on Gist using HTML Request to get Ajax data
authors:
- Josh Carr
resources:
- http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js
- http://cdnjs.cloudflare.com/ajax/libs/lodash.js/0.4.2/lodash.min.js
- http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js
- http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0.beta6/handlebars.min.js
- https://raw.github.com/tbranyen/backbone.layoutmanager/master/backbone.layoutmanager.js
normalize_css: no
[
{
"name": "Leaves of Grass",
"id": "2",
"author": "Walt Whitman"
},
{
"name": "The Cantos",
"id": "3",
"author": "Ezra Pound"
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment