Created
August 2, 2011 23:32
-
-
Save shanejonas/1121503 to your computer and use it in GitHub Desktop.
Working with backbone events in coffeescript
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
| # Heres how I've been working with arbitrary backbone events: | |
| # | |
| # Obviously in Backbone you can use events elsewhere as well, for | |
| # more info see the docs here: http://documentcloud.github.com/backbone/ | |
| # useful for running this with node.. else browser this with the right includes. | |
| # includes | |
| if typeof window is 'undefined' | |
| # npm install -g backbone | |
| # gives you: | |
| _ = require 'underscore' | |
| Backbone = require 'backbone' | |
| else | |
| console.log 'make sure you browser this with the right includes' | |
| #Empty 'event emitter' object | |
| EventEmitter = {} | |
| #Copy Backbone.Events object to EventEmitter | |
| _.extend EventEmitter, Backbone.Events | |
| #So now my EventEmitter object is a Backbone.Events object | |
| #You can just bind events, namespace them with the ':' and bind functions to happen when the events are triggered | |
| EventEmitter.bind 'hello:world', (message) -> | |
| # do something... | |
| console.log message | |
| # Ohs noes I clicked something, trigger my hello:world namespaced string with the message "hello" | |
| EventEmitter.trigger 'hello:world', 'hello' | |
| setTimeout -> | |
| # Ohs noes I clicked something a second later | |
| # trigger my hello:world namespaced string with the message "world" | |
| EventEmitter.trigger 'hello:world', 'world' | |
| , 1000 | |
| # | |
| # hello | |
| # #1s delay | |
| # world | |
| # | |
| # produces the following javascript: | |
| # | |
| # var Backbone, EventEmitter, _; | |
| # if (typeof window === 'undefined') { | |
| # _ = require('underscore'); | |
| # Backbone = require('backbone'); | |
| # } else { | |
| # console.log('make sure you browser this with the right includes'); | |
| # } | |
| # EventEmitter = {}; | |
| # _.extend(EventEmitter, Backbone.Events); | |
| # EventEmitter.bind('hello:world', function(message) { | |
| # return console.log(message); | |
| # }); | |
| # EventEmitter.trigger('hello:world', 'hello'); | |
| # setTimeout(function() { | |
| # return EventEmitter.trigger('hello:world', 'world'); | |
| # }, 1000); | |
| # # | |
| # |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment