Created
March 8, 2015 17:35
-
-
Save benmccormick/0948b37c75107a42b07e to your computer and use it in GitHub Desktop.
Declarative Radio handling for Marionette.Object
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
/* This is an experiment to shim support for handling Backbone.Radio | |
Events, Commands, and Requests onto Mn.Object. | |
Right now it only supports Object and not other Mn classes due to annoyances | |
of overriding the constructors of the different classes | |
It's also written in ES6 and uses my own import names for modules, so | |
it probably will not work for most people without some alteration as a result | |
*/ | |
import * as Mn from 'marionette'; | |
import * as Radio from 'radio'; | |
import * as _ from 'underscore'; | |
//Make Radio available declaratively on Mn.Object | |
let RadioMixin = { | |
constructor: function(options) { | |
this.options = _.extend({}, _.result(this, 'options'), options); | |
//right now we only care about supporting Object | |
//we can worry about other types later | |
if(this.proxyRadioHandler) { | |
this.proxyRadioHandlers(); | |
} | |
this.initialize.apply(this, arguments); | |
}, | |
_radioTypes: { | |
'radioEvents' : { | |
startMethod: 'on', | |
stopMethod: 'off' | |
}, | |
'radioCommands' : { | |
startMethod: 'comply', | |
stopMethod: 'stopComplying' | |
}, | |
'radioRequests' : { | |
startMethod: 'reply', | |
stopMethod: 'stopReplying' | |
} | |
}, | |
_radioChannels: [], | |
proxyRadioHandlers: function() { | |
this.unproxyRadioEvents(); | |
for (let radioType in this._radioTypes) { | |
let hash = _.result(this, radioType); | |
if (!hash) { | |
continue; | |
} | |
for (let key in hash) { | |
var method = hash[key]; | |
if (!_.isFunction(method)) { | |
method = this[hash[key]]; | |
} | |
if (!method) { | |
continue; | |
} | |
let [channel, messageName] = key.split(' '); | |
this.proxyRadioHandler(channel, radioType, messageName, method); | |
} | |
} | |
}, | |
proxyRadioHandler: function(channel, radioType, messageName, handler) { | |
let method = this._radioTypes[radioType].startMethod; | |
Radio[method](channel, messageName, handler, this); | |
}, | |
unproxyRadioEvents: function() { | |
_.each(this._radioChannels,(channel) => { | |
for(let radioType in this._radioTypes) { | |
let method = this._radioTypes[radioType].stopMethod; | |
Radio[method](channel,this); | |
} | |
}); | |
} | |
}; | |
Mn.Object = Mn.Object.extend(RadioMixin); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment