Skip to content

Instantly share code, notes, and snippets.

@paulfalgout
Created March 10, 2017 17:39
Show Gist options
  • Save paulfalgout/ccff747d03f52fcc9f40df916d16c1ed to your computer and use it in GitHub Desktop.
Save paulfalgout/ccff747d03f52fcc9f40df916d16c1ed to your computer and use it in GitHub Desktop.
Add radio-mixin to Mn 2.x Object
import _ from 'underscore';
import Marionette from 'marionette';
import RadioMixin from './radio-mixin';
const Obj = Marionette.Object.extend({
constructor(options) {
this.options = _.extend({}, _.result(this, 'options'), options);
this._initRadio();
Marionette.Object.prototype.constructor.apply(this, arguments);
}
});
_.extend(Obj.prototype, RadioMixin);
export default Obj;
import _ from 'underscore';
import Radio from 'backbone.radio';
import Marionette from 'marionette';
// Marionette v3 back-port of Marionette.Object Radio API
function _iterateReplies(target, channel, bindings, actionName) {
if(!channel || !bindings) return;
// type-check bindings
if(!_.isObject(bindings)) {
throw new Marionette.Error({
message: 'Bindings must be an object.',
url: 'marionette.functions.html#marionettebindradiorequests'
});
}
const normalizedRadioRequests = Marionette.normalizeMethods.call(target, bindings);
channel[actionName](normalizedRadioRequests, target);
}
export default {
_initRadio() {
const channelName = Marionette._getValue(this.getOption('channelName'), this);
if(!channelName) return;
const channel = this._channel = Radio.channel(channelName);
const radioEvents = Marionette._getValue(this.getOption('radioEvents'), this);
this.bindRadioEvents(channel, radioEvents);
const radioRequests = Marionette._getValue(this.getOption('radioRequests'), this);
this.bindRadioRequests(channel, radioRequests);
this.on('destroy', this._destroyRadio);
},
_destroyRadio() {
this._channel.stopReplying(null, null, this);
},
getChannel() {
return this._channel;
},
// Proxy `bindRadioEvents`
bindRadioEvents: Marionette.proxyBindEntityEvents,
// Proxy `unbindRadioEvents`
unbindEntityEvents: Marionette.proxyUnbindEntityEvents,
// Proxy `bindRadioRequests`
bindRadioRequests(channel, bindings) {
_iterateReplies(this, channel, bindings, 'reply');
},
// Proxy `unbindRadioRequests`
unbindEntityRequests(channel, bindings) {
_iterateReplies(this, channel, bindings, 'stopReplying');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment