Skip to content

Instantly share code, notes, and snippets.

@cobbweb
Created December 20, 2012 04:10
Show Gist options
  • Save cobbweb/4342930 to your computer and use it in GitHub Desktop.
Save cobbweb/4342930 to your computer and use it in GitHub Desktop.
Event-based nav object
MyApp.module('Nav', function(Nav, App) {
'use strict';
var render = Marionette.Renderer.render;
Nav.Navbar = Marionette.ItemView.extend({
template: 'nav/templates/navbar',
initialize: function()
{
this.items = {};
this._items = [];
_.bindAll(this, 'onRender');
this.bindTo(App.vent, 'nav:addItem', this.addItem, this);
this.bindTo(App.vent, 'nav:activateItem', this.activateItem, this);
},
addItem: function(name, href)
{
var $item = $(render('nav/templates/nav-item', { name: name, href: href }));
this.items[name] = $item;
this._items.push($item);
},
activateItem: function(name)
{
if (!(name in this.items)) {
throw new Error('Nav item titled ' + name + ' not registered');
}
this.$('li.active').removeClass('active');
this.items[name].addClass('active');
},
onRender: function()
{
_.invoke(this._items, 'appendTo', this.$('ul.nav'));
}
});
Nav.navbar = new Nav.Navbar();
});
// USAGE
SomeModule.addInitializer(function() {
App.vent.trigger('nav:addItem', 'People', '#people');
});
// In a router
App.vent.trigger('nav:activateItem', 'People');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment