Last active
August 29, 2015 14:10
-
-
Save ianmstew/0421b6d8cf4728651a08 to your computer and use it in GitHub Desktop.
HasChannel mixin
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
define(function (require, exports, module) { | |
var Radio = require('backbone.radio'); | |
var logger = require('lib/util/logger')(module); | |
// Supports a declarative channelName and semi-custom channelEvents hash. | |
// Example: | |
// channelName: 'notify' | |
// channelEvents: { | |
// 'error': ['on', 'onError'], | |
// 'show:message': ['comply', 'showMessage'] | |
// 'messages': ['reply', 'getMessages'] | |
// } | |
var HasChannel = { | |
// Declarative option for channel name | |
channelName: undefined, | |
// Declarative binding of channel events | |
// { 'event': ['on|reply|comply', eventHandler] } | |
channelEvents: undefined, | |
// Current channel | |
channel: undefined, | |
getChannel: function () { | |
return this.channel; | |
}, | |
// options { | |
// channelName: {string} Backbone.Radio channel name | |
// } | |
initialize: function (options) { | |
if (this.channelName) { | |
this.channelName = (options || {}).channelName || this.channelName; | |
this.channel = Radio.channel(this.channelName); | |
} | |
if (this.channelEvents) this._registerChannelEvents(); | |
}, | |
_registerChannelEvents: function (channelEvents) { | |
_.each(this.channelEvents, this._registerChannelEvent, this); | |
}, | |
_registerChannelEvent: function (channelHandler, event) { | |
var eventType = channelHandler[0]; | |
var eventHandler = _.isString(channelHandler[1]) | |
? this[channelHandler[1]] | |
: channelHandler[1]; | |
if (!_.isFunction(eventHandler)) { | |
throw new Error('Channel handler for "' + eventType + | |
'" must be an inline function or an instance method'); | |
} | |
switch (eventType) { | |
case 'on': | |
this.listenTo(this.channel, event, eventHandler); | |
break; | |
case 'reply': | |
this.replyFor(this.channel, event, eventHandler); | |
break; | |
case 'comply': | |
this.complyFor(this.channel, event, eventHandler); | |
break; | |
default: | |
logger.warn(eventType + ' is not supported'); | |
break; | |
} | |
} | |
}; | |
return HasChannel; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment