handling backbone model/collection changes in react.js

后端 未结 5 1936
旧巷少年郎
旧巷少年郎 2020-12-23 17:00

I\'ve been working with facebooks framework React.js together with Backbone for the last couple of weeks and I\'m still not entirely sure what is the most appropriate way to

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-23 17:44

    There's another BackboneMixin, courtesy of Eldar Djafarov, that re-renders your component when the model changes and also provides a very convenient way to get two-way databinding:

      var BackboneMixin = {
        /* Forces an update when the underlying Backbone model instance has
         * changed. Users will have to implement getBackboneModels().
         * Also requires that React is loaded with addons.
         */
        __syncedModels: [],
        componentDidMount: function() {
          // Whenever there may be a change in the Backbone data, trigger a reconcile.
          this.getBackboneModels().forEach(this.injectModel, this);
        },
        componentWillUnmount: function() {
          // Ensure that we clean up any dangling references when the component is
          // destroyed.
          this.__syncedModels.forEach(function(model) {
            model.off(null, model.__updater, this);
          }, this);
        },
        injectModel: function(model){
          if(!~this.__syncedModels.indexOf(model)){
            var updater = this.forceUpdate.bind(this, null);
            model.__updater = updater;
            model.on('add change remove', updater, this);
          }
        },
        bindTo: function(model, key){
          /* Allows for two-way databinding for Backbone models.
           * Use by passing it as a 'valueLink' property, e.g.:
           *   valueLink={this.bindTo(model, attribute)} */
          return {
            value: model.get(key),
            requestChange: function(value){
                model.set(key, value);
            }.bind(this)
          };
        }
      }
    

    Here's his jsFiddle that demonstrates the usage: http://jsfiddle.net/djkojb/qZf48/13/

提交回复
热议问题