-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.js
108 lines (89 loc) · 2.22 KB
/
main.js
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
* 定义一个数组,用于存放数据
*/
var TodoList = [];
/*
* actions
*/
var actions = {
addTodo: function(text) {
return {type: 'add', text: text };
},
delTodo: function(id) {
return { type: 'del', id: id };
},
editTodo: function(id, text) {
return { type: 'del', id: id, text: text };
},
showTodo: function() {
return { type: 'show', data: TodoList };
}
}
//初始state
var initialState = {
data: TodoList,
id: 0
}
/*
* reducer
*/
function todoReducer (state, action) {
if (state === undefined) {
state = initialState;
}
switch (action.type) {
case 'add':
state.data.push({id: state.id + 1, text: action.text})
state.id = state.id + 1;
return state
case 'del':
for (var i = 0; i < state.data.length; i++) {
if (action.id === state.data[i].id) {
state.data.splice(i, 1);
}
}
return state
case 'edit':
for (var i = 0; i < state.data.length; i++) {
if (action.id === state.data[i].id) {
state.data[i].text = action.text;
}
}
return state
default:
return state
}
}
/*
* 创建store
*/
var store = Redux.createStore(todoReducer)
console.log(store.getState());
store.dispatch(actions.addTodo('redux-jQuery-demo'));
console.log(store.getState());
renderList(store.getState());
/*
* 页面上用到的方法
*/
function renderList(state) {
var data = state.data;
var ul = $('#todo-ul');
ul.empty();
data.forEach(function(item){
ul.append('<li todoid="' + item.id + '" class="list-group-item">' + item.text + '<span class="badge" onclick="delTodo()">删除</span></li>');
});
}
function addTodo() {
var state;
var text = $('#new-todo').val();
store.dispatch(actions.addTodo(text));
state = store.getState();
renderList(state);
}
function delTodo() {
var e = window.event;
var id = parseInt($(e.target).parent().attr('todoid'), 10);
store.dispatch(actions.delTodo(id));
state = store.getState();
renderList(state);
}