Slide 41
Slide 41 text
myApp.views.NavBar = Backbone.View.extend({
templateName: "navBar",
className: "nav-bar",
events: {
"click .profile" : "showProfileMenu",
"click .main-logo" : "goHome"
},
initialize : function() {
this.model.bind('change', this.render);
this.render();
},
render : function() {
this.template = JST[this.templateName];
this.$el.html(this.template(this.model));
return this;
}
});
Wednesday, April 25, 2012
Ok, now, this is getting more complicated. This view object extends Backbone.View, just like
our user model extended Backbone.Model. Then we’re passing it an object that has overrides
for the Backbone default view code. So we name the template this view uses, we tell it what
class to put on the div it creates when it renders, then we tell it about some DOM events that
we care about, then we override the initialize method, and then we override the render
method.
Now that events object is built in to backbone views. The keys are the DOM events you care
about that happen within this view, and these can be custom events, along with the selector
you expect them to happen on. So click .profile means any click event on an element with
class profile, within this view. Then the values of this object are strings that are names of
functions to call when that event occurs.
So, I didn’t have space on the slide for it, but this view would have a showProfileMenu
function, and a goHome function.
So in our initialize, which, you remeber, was called in the app object’s initialize, we do two
things: we bind to our model’s change event, and we render the view. Now the view’s model
is the current user object, and we passed that into this intialize.