Last active
August 29, 2015 14:05
-
-
Save JaapRood/cc8fe4533d45508f3f51 to your computer and use it in GitHub Desktop.
A way to use AmpersandState and React together a bit more easily by mixing in Backbone's Event
This file contains hidden or 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
// Not tested, but the main gist of glueing ampersand state and react components together well. The actual mixin I use in production is slightly more eleborate (handling the stopping of listening and rebinding through the component's lifecycle), but the main idea is there. | |
var Events = require('backbone-events-standalone'), | |
React = require('react'), | |
State = require('ampersand-state'); | |
var PostModel = State.extend({ | |
props: { | |
title: 'string', | |
body: 'string' | |
} | |
}); | |
var Post = React.createClass({ | |
mixins: [Events], | |
render: function() { | |
// render it | |
}, | |
componentDidMount: function() { | |
var component = this; | |
// we could bind this, but then the event's arguments get passed, | |
// which isn't what we want | |
var forceUpdate = function() { component.forceUpdate(); }; | |
// listenTo so | |
this.listenTo(this.props.post, 'change', forceUpdate); | |
}, | |
componentWillUnmount: function() { | |
this.stopListening(); | |
} | |
}); | |
doucment.addEventListener('DOMContentLoaded', function() { | |
React.renderComponent(Post({post: new PostModel()}), document.body); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment