Here is my solution. Thanks to this, the state of Observable the React is automatically updated (with its consequences, for example, with the reprocessing of a component), and you can even listen to changes out of response thanks to the .on method.
var eventEmitter = { _JQInit: function() { this._JQ = jQuery(this); }, emit: function(evt, data) { !this._JQ && this._JQInit(); this._JQ.trigger(evt, data); }, once: function(evt, handler) { !this._JQ && this._JQInit(); this._JQ.one(evt, handler); }, on: function(evt, handler) { !this._JQ && this._JQInit(); this._JQ.bind(evt, handler); }, off: function(evt, handler) { !this._JQ && this._JQInit(); this._JQ.unbind(evt, handler); } }; var Observable = function(initialValue, name) { var self = eventEmitter; var name = name; var obj = { value: initialValue, ops: self }; self.get = function() { return obj.value }; self.set = function(updated){ if(obj.value == updated) return; obj.value = updated; self.emit('change', updated); }; self.mixin = function() { var mixin = { getInitialState: function() { var obj_ret = {}; obj_ret[name] = obj; return obj_ret; }, componentDidMount : function() { self.on('change', function() { var obj_new = {}; obj_new[name] = obj; this.setState(obj_new); }.bind(this)); } }; return mixin; }; return self; };
Example
(using it to display a warning on another component): // Observed init alert_msg = Observed ('', 'alertmsg');
var ConfirmBtn = React.createClass({ mixins: [alert_msg.mixin()], handleConfirm: function(e) { e.preventDefault(); this.state.alertmsg.ops.set(null); if(! $('#cgv').is(':checked')) { this.state.alertmsg.ops.set('Please accept our terms of conditions'); return; } } } var AlertPayment = React.createClass({ mixins: [alert_msg.mixin()], render: function() { var style = (this.state.alertmsg === null) ? {display: 'none'} : {display: 'block'}; return ( <div style={style} className="alertAcceptTerms"> {this.state.alertmsg.value} </div> ); } });
Hope this helps
source share