-
-
Save cuppster/3364166 to your computer and use it in GitHub Desktop.
Routed Commands for Backbone.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
}); | |
} | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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