Advertisement
Guest User

Untitled

a guest
Jul 27th, 2015
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. function emitter(obj){
  2. var store = {}
  3. obj.on = function (e, cb) {
  4. add(e, cb, true)
  5. }
  6. obj.one = function (e, cb) {
  7. add(e, cb, false)
  8. }
  9. obj.off = function (e) {
  10. delete store[e]
  11. }
  12. obj.emit = function (e) {
  13. var events = store[e] || []
  14. var args = Array.prototype.slice.call(arguments, 1)
  15. events.forEach(function(cb, i) {
  16. cb(args, i)
  17. })
  18. }
  19. return obj
  20.  
  21. function add(e, cb, t) {
  22. store[e] = store[e] || []
  23. store[e].push(function (args, i) {
  24. cb.apply(obj, args)
  25. if (!t) store[e].splice(i,1)
  26. })
  27. }
  28. }
  29.  
  30. var a = emitter({
  31. some: 123
  32. })
  33. a.on('roof-on-fire', function () {
  34. console.log('put the fire', this.some)
  35. })
  36. a.one('roof-on-fire', function (data) {
  37. console.log('call the fireman', data)
  38. })
  39. a.emit('roof-on-fire', { address: '560, Mission st.'})
  40. a.off('roof-on-fire')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement