Created
October 31, 2012 11:26
-
-
Save asciidisco/3986542 to your computer and use it in GitHub Desktop.
PubSub with requirejs & backbone
This file contains 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
// PubSub impl. with require.js & backbone.js | |
// events.js | |
define(['underscore', 'backbone'], function (_, Backbone) { | |
'use strict'; | |
var events = {}; | |
_.extend(events, Backbone.Events); | |
return events; | |
}); | |
// filea.js | |
define(['events'], function (events) { | |
'use strict'; | |
events.on('my:event', function (message) { | |
console.log('Received message: ', message); | |
}); | |
}); | |
// fileb.js | |
define(['filea', 'events'], function (filea, events) { | |
'use strict'; | |
events.trigger('my:event', 'My Message'); | |
}); |
I try to avoid globals as much as possible, so I don´t have a javascript MyAppName
global in my current projects.
The application where I use this right now consists of a few modules/widgets, so i go with a naming scheme like:
shell MyWdget:Emitter:operation
For example: shell Comments:Comment:add
, when a new comment has been added to the collection of the comments widget.
Whoops, this javascript
and shell
things shouldn´t be there, copy & pasten errors...
This works extremely well.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Seems fine to me, I normally have something like
MyAppName.vent
which I use for generic PubSub. The only issue with generic PubSub is that while it keeps your code decoupled; it's hard to document and maintain, and come up with a consistent naming convention. How do you normally name your events?