Skip to content

Instantly share code, notes, and snippets.

@dkleehammer
Created July 31, 2013 22:08
Show Gist options
  • Save dkleehammer/6126639 to your computer and use it in GitHub Desktop.
Save dkleehammer/6126639 to your computer and use it in GitHub Desktop.
Backbone/Marionette JS session handling example
define([
'marionette',
'router',
'controller',
'modules/auth',
'modules/vent',
'views/_layout'
], function(Marionette, Router, Controller, Auth, Vent, Layout){
var App = new Marionette.Application();
App.Auth = Auth;
App.Auth.getAuth();
App.addRegions({
wrapper: '#wrapper'
});
App.addInitializer(function() {
// start our router
new Router({controller: Controller.initialize(App)});
App.bind("initialize:after", function(options) {
var layout = new Layout();
App.wrapper.show(layout);
});
// start our backbone history for our router
if (Backbone.history){
Backbone.history.start({pushState: true});
}
});
Vent.on('logout', function() {
Auth.logout();
});
Auth.on('change:logged_in', function(){
console.log('logged in changed: ', Auth.get('logged_in'));
console.log(Auth.attributes);
});
return App;
});
define(['models/session'], function(SessionModel){
return SessionModel;
});
require.config({
paths: {
jquery: 'libs/jquery/jquery-loader',
underscore: 'libs/underscore/underscore-min',
backbone: 'libs/backbone/backbone-min',
wreqr: 'libs/marionette/backbone.wreqr',
marionette: 'libs/marionette/backbone.marionette',
handlebars: 'libs/handlebars/handlebars',
text: 'libs/require/text'
},
shim: {
jquery: {
exports: 'jQuery'
},
underscore: {
exports: '_'
},
backbone: {
deps: ['jquery', 'underscore'],
exports: 'Backbone'
},
wreqr: {
deps: ['backbone']
},
marionette: {
deps: ['backbone', 'wreqr'],
exports: 'Marionette'
},
handlebars: {
deps: ['jquery', 'marionette'],
exports: 'Handlebars'
}
},
urlArgs: '_=' + (new Date().getTime())
});
require([
'underscore',
'marionette',
'handlebars',
'app'
], function(_, Marionette, Handlebars, App){
// setup our templates to use curly braces
_.templateSettings = {
evaluate : /\{\[([\s\S]+?)\]\}/g,
interpolate : /\{\{([\s\S]+?)\}\}/g
};
// enables loading templates using ajax.
Marionette.TemplateCache.prototype.loadTemplate = function(templateId, callback) {
var template = templateId;
// Make sure we have a template before trying to compile it
if (!template || template.length === 0) {
var msg = "Could not find template: '" + templateId + "'";
var err = new Error(msg);
err.name = "NoTemplateError";
throw err;
}
return template;
};
// enables handlebars as our template library
Marionette.TemplateCache.prototype.compileTemplate = function(rawTemplate) {
return Handlebars.compile(rawTemplate);
};
// handlebars helper dateFormat (momentjs)
Handlebars.registerHelper('dateFormat', function(context, block) {
if (window.moment) {
var f = block.hash.format || "MMM DD, YYYY hh:mm:ss A";
return moment(context).format(f); //had to remove Date(context)
}else{
return context; // moment plugin not available. return data as is.
};
});
App.Auth.on('change', _.once(function(){
App.start();
}));
});
define([
'backbone'
], function(Backbone) {
var SessionModel = Backbone.Model.extend({
urlRoot: '/api/session',
initialize: function () {
var that = this;
// Hook into jquery
// Use withCredentials to send the server cookies
// The server must allow this through response headers
$.ajaxPrefilter(function( options, originalOptions, jqXHR) {
options.xhrFields = {
withCredentials: true
};
});
},
login: function(creds) {
// Do a POST to /api/session and send the serialized form creds
var that = this;
this.save(creds, {
success: function (model, resp) {
if (resp.success == false) {
alert(resp.message);
}
that.unset('password');
that.set(resp.data);
}
});
},
logout: function() {
// Do a DELETE to /api/session and clear the client side data
var that = this;
this.destroy({
success: function (model, resp) {
model.clear({silent:true});
// Set auth to false to trigger a change:logged_in event
// The server also returns a new csrf token so that
// the user can relogin without refreshing the page
that.set({logged_in: false});
}
});
},
getAuth: function(callback) {
// getAuth is wrapped around our router
// before we start any routers let us see if the user is valid
this.fetch({
success: callback
});
}
});
return new SessionModel;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment