Skip to content

Instantly share code, notes, and snippets.

@jyek
Created January 5, 2017 14:32
Show Gist options
  • Save jyek/59616bc5698223eb6239f1bd875ebd6c to your computer and use it in GitHub Desktop.
Save jyek/59616bc5698223eb6239f1bd875ebd6c to your computer and use it in GitHub Desktop.
Backbone React ES6
'use strict'
var React = require('react');
/**
* Backbone React Component
*
* Override getBackboneState to tell the mixin
* HOW to transform Backbone props into JSON state
*
* getBackboneState(props) {
* var stampModel = props.stampModel,
* primaryZineModel = stampModel.getPrimaryZine();
*
* return {
* stamp: stampModel.toJSON(),
* toggleIsLiked: stampModel.toggleIsLiked.bind(stampModel),
* primaryZine: primaryZineModel && primaryZineModel.toJSON()
* };
* }
*
* Optionally override watchBackboneProps to tell the mixin
* WHEN to transform Backbone props into JSON state
*
* watchBackboneProps(props, listenTo) {
* listenTo(props.stampModel, 'change:unauth_like_count change:is_liked');
* listenTo(props.stampModel.get('zines'), 'all');
* }
*/
class BackboneComponent extends React.Component {
componentDidMount() {
if (!_.isFunction(this.getBackboneState)) {
throw new Error('You must provide getBackboneState(props).');
}
this._bindBackboneEvents(this.props);
}
componentWillReceiveProps(newProps) {
this._unbindBackboneEvents();
this._bindBackboneEvents(newProps);
}
componentWillUnmount() {
this._unbindBackboneEvents();
}
_updateBackboneState() {
var state = this.getBackboneState(this.props);
this.setState(state);
}
_bindBackboneEvents(props) {
if (!_.isFunction(this.watchBackboneProps)) {
return;
}
if (this._backboneListener) {
throw new Error('Listener already exists.');
}
if (!props) {
throw new Error('Passed props are empty');
}
var listener = _.extend({}, Backbone.Events),
listenTo = _.partial(listener.listenTo.bind(listener), _, _, this._updateBackboneState.bind(this));
this.watchBackboneProps(props, listenTo);
this._backboneListener = listener;
}
_unbindBackboneEvents() {
if (!_.isFunction(this.watchBackboneProps)) {
return;
}
if (!this._backboneListener) {
throw new Error('Listener does not exist.');
}
this._backboneListener.stopListening();
delete this._backboneListener;
}
};
module.exports = BackboneComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment