codecombat/app/lib/CocoClass.coffee

66 lines
1.8 KiB
CoffeeScript
Raw Normal View History

2014-01-03 13:32:13 -05:00
# Template for classes with common functions, like hooking into the Mediator.
utils = require './utils'
classCount = 0
makeScopeName = -> "class-scope-#{classCount++}"
doNothing = ->
2014-01-03 13:32:13 -05:00
module.exports = class CocoClass
subscriptions: {}
shortcuts: {}
2014-01-03 13:32:13 -05:00
# setup/teardown
constructor: ->
@subscriptions = utils.combineAncestralObject(@, 'subscriptions')
@shortcuts = utils.combineAncestralObject(@, 'shortcuts')
@listenToSubscriptions()
@scope = makeScopeName()
@listenToShortcuts()
_.extend(@, Backbone.Events) if Backbone?
destroy: ->
# teardown subscriptions, prevent new ones
@stopListening?()
@off()
2014-01-03 13:32:13 -05:00
@unsubscribeAll()
@stopListeningToShortcuts()
@[key] = undefined for key of @
@destroyed = true
@off = doNothing
@destroy = doNothing
2014-01-03 13:32:13 -05:00
# subscriptions
2014-01-03 13:32:13 -05:00
listenToSubscriptions: ->
# for initting subscriptions
return unless Backbone?.Mediator?
for channel, func of @subscriptions
func = utils.normalizeFunc(func, @)
Backbone.Mediator.subscribe(channel, func, @)
addNewSubscription: (channel, func) ->
# this is for adding subscriptions on the fly, rather than at init
return unless Backbone?.Mediator?
return if @destroyed
return unless @subscriptions[channel] is undefined
func = utils.normalizeFunc(func, @)
@subscriptions[channel] = func
Backbone.Mediator.subscribe(channel, func, @)
unsubscribeAll: ->
for channel, func of @subscriptions
func = utils.normalizeFunc(func, @)
Backbone.Mediator.unsubscribe(channel, func, @)
2014-01-03 13:32:13 -05:00
# keymaster shortcuts
listenToShortcuts: ->
return unless key?
for shortcut, func of @shortcuts
func = utils.normalizeFunc(func, @)
key(shortcut, @scope, _.bind(func, @))
2014-01-03 13:32:13 -05:00
stopListeningToShortcuts: ->
return unless key?
key.deleteScope(@scope)