Skip to content

Instantly share code, notes, and snippets.

@fordguo
Forked from jgwhite/app.js
Created May 5, 2014 02:59
Show Gist options
  • Save fordguo/21d7660fdfb5eb0187d9 to your computer and use it in GitHub Desktop.
Save fordguo/21d7660fdfb5eb0187d9 to your computer and use it in GitHub Desktop.
var App = Em.Application.create();
App.ApplicationController = Em.Controller.extend();
App.ApplicationView = Em.View.extend({ templateName: 'application' });
App.HomeController = Em.Controller.extend();
App.HomeView = Em.View.extend({ templateName: 'home' });
App.AuthController = Em.Controller.extend({
authenticated: false,
failedAttempts: 0,
authenticate: function() {
if (this.credentialsValid()) {
this.set('authenticated', true);
} else {
this.incrementProperty('failedAttempts');
}
},
credentialsValid: function() {
return this.get('email') === 'jamie@jgwhite.co.uk'
&& this.get('password') === 'ilovejam';
},
authenticatedDidChange: function() {
if (this.get('authenticated')) {
this.get('target').send('becomeAuthenticated');
}
}.observes('authenticated')
});
App.AuthView = Em.View.extend({
tagName: 'form',
templateName: 'auth'
});
App.TextField = Em.TextField.extend({
attributeBindings: ['type', 'value', 'size', 'autofocus']
})
App.Router = Em.Router.extend({
root: Em.Route.extend({
// The unknown default state; neither authenticated nor unauthenticated.
// The router knows to enter this state by default, then the unknown
// state can decide whether to enter authenticated or unauthenticated mode.
default: Em.Route.extend({
route: '/',
enter: function(router) {
var authenticated = router.get('authController').get('authenticated');
// It's not at all obvious why this works :(
Em.run.next(function() {
if (authenticated) {
router.transitionTo('authenticated');
} else {
router.transitionTo('unauthenticated');
}
})
}
}),
authenticated: Em.Route.extend({
initialState: 'home',
home: Em.Route.extend({
route: '/home',
connectOutlets: function(router) {
router.get('applicationController').connectOutlet('home');
}
})
}),
unauthenticated: Em.Route.extend({
initialState: 'auth',
auth: Em.Route.extend({
route: '/auth',
connectOutlets: function(router) {
router.get('applicationController').connectOutlet('auth');
}
}),
authenticate: function(router) {
router.get('authController').authenticate();
},
becomeAuthenticated: function(router) {
router.transitionTo('authenticated');
}
})
})
});
App.initialize();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment