gpt4 book ai didi

javascript - 绑定(bind)事件发射器上的单个事件

转载 作者:行者123 更新时间:2023-11-28 07:40:03 24 4
gpt4 key购买 nike

React 组件需要事件来接收来自其他对象的状态更改。为了使组件可重用,我想在组件外部定义触发状态更改的事件类型/名称。所以我正在考虑一个绑定(bind)事件发射器和事件类型/名称的类。 React 组件只需要调用 .on,不需要任何事件类型/名称。将更多事件合并为一个事件也是有意义的。我没有在框架中见过这些通用类,所以我不确定是否还有其他设计模式,我只是用错误的关键字进行了搜索。

这是处理通用 React 组件事件的正确方法吗?

这是一个示例,以便您有更好的想法:

var emitter = {};
_.extend(emitter, Backbone.Events);

var Component = React.createClass({
getInitialState: function () {
var self = this;
self.props.update.on(function (text) {
self.setState({text: text});
});
return {text: ''};
},
render: function () {
return React.DOM.p({}, this.state.text != null ? this.state.text : '');
}
});*

// this would require to know the event type/name in the component
//var component = React.createFactory(Component)({update: emitter});

var binding = new Event(emitter, 'label:changed');
var component = React.createFactory(Component)({update: binding});

// this would merge multiple events into a single one
/*var binding = Event.merge([
new Event(emitter, 'label:changed'),
new Event(emitter, 'label:deleted')]);*/

var component = React.createFactory(Component)({update: binding});

最佳答案

你熟悉Flux architecture吗? ?它在 Stores 中使用事件发射器那一个Controller-view可以听。这是您所描述内容的一个很好的例子。

Controller View 是一个顶级组件,它监听新事件,然后通过 props 将数据传递到较低级别的组件。

无论您是否实现 Flux,Facebook 在其 Todo List Example 中都有一些很好的示例可以回答您的问题。 .

关于javascript - 绑定(bind)事件发射器上的单个事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28170605/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com