I'm new at Backbone.js. So I want to ask a question about problem which I face with.
I have a User object which is exteded from Backbone.Model. According to the state of this object( authenticated or not), I want to change my views. I have showView method which enable my views to be rendered.
For this structure how I change my HomeView's template and enable it to be rendered according to the model. I think, just adding below code is not sufficient for this.
this.user.bind('change', this.render);
Any idea or help will be greately appreciated.
My Router
var AppRouter = Backbone.Router.extend({
routes: {
'':'showHome',
'join':'showJoin',
'join/create':'showRegister',
'join/complete':'showLoginComplete',
// Define some URL routes
// 'users': 'showContributors',
// Default
':actions': 'defaultAction'
},
showView: function(view) {
if (this.currentView)
{
this.currentView.close();
$('#tomato').attr("style",";display:none;");
$('#tomato').html(view.render().el);
$("#tomato").fadeIn("slow");
}else{
$('#tomato').html(view.render().el);
}
this.currentView = view;
return view;
},
login_required: function(callback) {
if (this.user.get('is_authenticated')) {
if (callback) callback();
} else {
//route login page...
}
},
login_not_required:function(callback){
if (this.user.get('is_authenticated')) {
//route 404 page...
this.navigate(':actions', true);
} else {
if (callback) callback();
}
},
updateUser:function(){
var $self=this;
$.get(
'/get_identity',
function(response){
// update model...
$self.user.id =response.identity;
//check user every five minutes...
$self.user.fetch({success: function() {
$self.user.set('is_authenticated',true);
setTimeout($self.updateUser, 1000*60*5);
}
},this);
}).fail(function(){
//clear model
$self.user.clear().set($self.user.defaults);
});
}
});
var initialize = function(){
//initialize user and it's checker.
var app_router = new AppRouter;
this.user = new User();
_.bindAll(app_router, 'updateUser');
app_router.updateUser();
app_router.on('route:showHome', function(){
var homeView = new HomeView({user:app_router.user});
app_router.showView(homeView);
});
};
return {
initialize: initialize
};
});
My HomeView
var HomeView = Backbone.View.extend({
initialize:function(){
this.user = this.options.user
}
render: function(){
var headerView = new HeaderView();
var footerView = new FooterView();
this.$el.append(headerView.render().$el);
this.$el.append(homeTemplate);
this.$el.append(footerView.render().$el);
return this;
}
});