e:
var e = _.extend({}, Backbone.Events);
e.on('user:loggedIn', function() {
ws.navigate('/dashboard', true);
});
Router:
var Workspace = Backbone.Router.extend({
_e: null,
_userStatus: null,
routes: {
"":"login",
"dashboard":"dashboard",
},
initialize: function(e) {
this._e = e;
this._userStatus = new UserStatus({e: e});
$('.back').live('tap', function(e) {
window.history.back();
return false;
});
},
login: function() {
console.log('LoginPage');
var userLoginView = new UserLoginView({userStatus: this._userStatus});
userLoginView.render();
var transition = $.mobile.defaultPageTransition;
$.mobile.changePage($(userLoginView.el), {changeHash:false, transition: transition});
},
dashboard: function() {
console.log('DashboardPage');
var dashboardView = new DashboardView();
dashboardView.render();
var transition = $.mobile.defaultPageTransition;
$.mobile.changePage($(dashboardView.el), {changeHash:false, transition: transition});
},
});
Model UserStatus:
window.UserStatus = Backbone.Model.extend({
_e: null,
defaults: {
loggedIn: false,
token: null
},
initialize: function(e) {
console.log('I\'m initialized');
this._e = e;
_.bindAll(this, 'onTokenChange');
this.on('change:token', this.onTokenChange, this);
this.set({'token': localStorage.getItem('token')});
},
onTokenChange: function(status, token) {
console.log('this is the token: ' + token);
this.set({'loggedIn': !!token});
if(this.get('loggedIn')) {
//console.log(this._self.get('loggedIn'));
this._e.trigger('user:loggedIn');
}
},
setToken: function(token) {
localStorage.setItem('token', token);
this.set({'token': token});
}
});
UserLoginView:
window.UserLoginView = Backbone.View.extend({
_appId: 239865876123221,
_userStatus: null,
initialize: function(userStatus) {
console.log('Initializing Login View');
_.bindAll(this, 'render', 'onPageHide', 'onLogin');
this._userStatus = userStatus;
},
events: {
'pagehide':'onPageHide',
'tap #fb-login': 'onLogin'
},
render: function() {
$(this.el).html(this.template);
$(this.el).attr('data-role', 'page');
$('body').append($(this.el));
$(this.el).page();
return this;
},
onPageHide: function() {
$(this.el).remove();
},
onLogin: function() {
window.plugins.facebook.authorize(this._appId, function(res) {
if(res.token !== undefined) {
// we have a token, save it (user has authenticated before)
this._userStatus.setToken(res.token);
} else {
// we have to call authorize
window.plugins.facebook.getAccess(function(res) {
if(res.token !== undefined) {
// We got a token (user has authenticated just in a moment)
console.log('User has authenticated just in a moment -> ' + res.token);
this._userStatus.setToken(res.token);
}
});
}
});
}
});