在reactjs组件中侦听模型

时间:2014-05-14 13:40:21

标签: reactjs

我正在尝试使用reactjs,尝试用它制作基于MVC的纸牌游戏。我发现ReactJS是一个非常强大且性能良好的视图库,但我有一些麻烦将它映射到更传统的MVC模式,其中视图听取模型。

在纸牌游戏中,桌面上有两排牌,一个是当前玩家,一个是对手玩家。当前玩家的牌位于底行,可以选择。在我的GameView中,我渲染了2个子视图,如下所示:

<SlotView key="slotview1" slot={this.state.otherPlayer.slot} selectable={false} /> <SlotView key="slotview2" slot={this.state.currentPlayer.slot} selectable={this.state.playing_cards} on_select={this.handlePlayCard}>

当转弯结束时,我交换当前玩家和其他玩家(在游戏模型中)并通过事件通知游戏视图。游戏视图的状态更新,然后从其他玩家的角度重新渲染自己。

这很好用,其他玩家的牌显示在底行。但是,我遇到的问题是SlotView(游戏视图的子视图)也会监听它的模型(它在播放卡时会自动更新)。

我在SlotView#ComponentDidMount中绑定侦听器并在SlotView#ComponentDidUnmount中取消绑定它们。但是,组件仅在第一次渲染期间安装,并且从不卸载并再次安装。它的属性(插槽)正在更新到其他播放器,但它仍然会侦听来自第一个播放器的事件。有没有办法可以监听属性更改来绑定/取消绑定事件处理程序?或者我不应该在子组件中监听模型并用更推送的模型替换MVC模型(但这似乎产生了许多带有嵌套视图的样板代码)? 我应该在渲染方法本身解绑/重新绑定(但这似乎也错了)?

很想知道其他人是如何做到的......

1 个答案:

答案 0 :(得分:1)

我忽略了API调用(componentWillReceiveProps)。 所以在我的SlotView中,我使用以下逻辑来监听/停止收听插槽模型。 仍然很想知道是否有更好的模式可能。

componentWillReceiveProps: function(nextProps) {
  if (nextProps.slot && nextProps.slot != this.props.slot) {
    this.props.slot.removeListener('change', this.slotListener);
    nextProps.slot.on("change",this.slotListener);
  }
},


slotListener : function (data) {
  this.setState({ selectedIndex: -1 })
},


componentDidMount: function () {
  var self = this;
  this.props.slot.on("change",this.slotListener)

},

componentWillUnmount: function () {
  this.props.slot.removeListener('change', this.slotListener);
},