Skip to content

Instantly share code, notes, and snippets.

@cuppster
Created August 15, 2012 22:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cuppster/3364166 to your computer and use it in GitHub Desktop.
Save cuppster/3364166 to your computer and use it in GitHub Desktop.
Routed Commands for Backbone.js
// the application
//
var AppView = Backbone.View.extend({
el: $('body'),
initialize: function() {
var view = this;
// command bar
this.controls = new ControlsView({
// there are links below ul.nav that have a 'data-event' attribute set
'el': this.$el.find('ul.nav')
});
// a target for the command
this.commandTarget = new CommandTargetView({
// #target is the view that will receive events from the controls
el: $('#target')
});
// render sub-view, triggers subscribe event caught above
this.commandTarget.render();
}
});
// controls
//
var ControlsView = Backbone.View.extend({
events: {
// click will trigger an event named in the 'data-event' attribute of the link
'click [data-event]': function(e) {
e.preventDefault();
var event = $(e.currentTarget).data('event');
if (this.delegate) this.delegate.$el.trigger(event);
}
},
initialize: function() {
var view = this;
// capture subscribe event on BODY
$('body').on('toolbar.subscribe', function(e, subview) {
// set delegate
view.delegate = subview;
});
}
});
// command target
//
var CommandTargetView = Backbone.View.extend({
events: {
'command1': function() {
alert('received command1');
},
'command2': function() {
alert('received command2');
},
},
// when rendered, I want to receive commmands...
render: function() {
this.$el.trigger('toolbar.subscribe', this);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment