展示一个Reflux的实例【虽然用的人比较少】

Reflux是根据React的flux创建的单向数据流类库。

Reflux的单向数据流模式主要由actions和stores组成。例如,当组件list新增item时,会调用actions的某个方法(如addItem(data)),并将新的数据当参数传递进去,通过事件机制,数据会传递到stroes中,stores可以向服务器发起请求,并更新数据数据库。数据更新成功后,还是通过事件机制传递的组件list当中,并更新ui。整个过程的对接是通过事件驱动的。

这里记录一个比较实用的实例;具体的想看详情的可以去‘http://segmentfault.com/a/1190000002793786#articleHeader24’这里仔细研读。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
var TodoActions = Reflux.createActions([
'getAll',
'addItem',
'deleteItem',
'updateItem'
]);
var TodoStore = Reflux.createStore({
items: [1, 2, 3],
listenables: [TodoActions],
onGetAll: function () {
$.get('/all', function (data) {
this.items = data;
this.trigger(this.items);
}.bind(this));
},
onAddItem: function (model) {
$.post('/add', model, function (data) {
this.items.unshift(data);
this.trigger(this.items);
}.bind(this));
},
onDeleteItem: function (model, index) {
$.post('/delete', model, function (data) {
this.items.splice(index, 1);
this.trigger(this.items);
}.bind(this));
},
onUpdateItem: function (model, index) {
$.post('/update', model, function (data) {
this.items[index] = data;
this.trigger(this.items);
}.bind(this));
}
});
var TodoComponent = React.createClass({
mixins: [Reflux.connect(TodoStore, 'list')],
getInitialState: function () {
return {list: []};
},
componentDidMount: function () {
TodoActions.getAll();
},
render: function () {
return (
<div>
{this.state.list.map(function(item){
return <TodoItem data={item}/>
})}
</div>
)
}
});
var TodoItem = React.createClass({
componentDidMount: function () {
TodoActions.getAll();
},
handleAdd: function (model) {
TodoActions.addItem(model);
},
handleDelete: function (model,index) {
TodoActions.deleteItem(model,index);
},
handleUpdate: function (model) {
TodoActions.updateItem(model);
},
render: function () {
var item=this.props.data;
return (
<div>
<p>{item.name}</p>
<p>{item.email}</p>
<p>/*操作按钮*/</p>
</div>
)
}
});
React.render(<TodoComponent />, document.getElementById('container'));