//简单运用redux写了一个加减乘除功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jisuanji</title>
<script src="http://cdn.bootcss.com/redux/3.6.0/redux.js"></script>
</head>
<body>
<h1>加减乘除例子</h1>
<input type="text" id="num1" name="" onchange="compute()" />
<select name="" id="selection" onchange="compute()">
<option value="add" selected="selected">加</option>
<option value="minus">减</option>
<option value="multiply">乘</option>
<option value="divide">除</option>
</select>
<input type="text" id="num2" name="" onchange="compute()" />
<label>=</label>
<label name="goal" id="value"></label>
<script type="text/javascript">
// reducer 根据当前state和action计算出nextstate
function countReducer(state,action){
if(state==="undefined"){
return 0;
}
switch(action.type){
// action javacsript对象 redux规定他必须含有一个字符串值type属性
case "ADD":
return Number(action.num1)+Number(action.num2)//为什么要用number,因为所有的html文本都是字符串类型,必须转化为数字
case "MINUS":
return action.num1 - action.num2
case "MULTIPLY":
return action.num1 * action.num2
case "DIVIDE":
return action.num1 / action.num2
default:
return state
}
}
var store = Redux.createStore(countReducer);
var valueEl = document.getElementById("value");
function render(){
valueEl.innerHTML = store.getState();
}
// render()
store.subscribe(render)//dispatch时,调用此处添加的监听函数
function compute(){
var num1Value = document.getElementById("num1").value;
var num2Value = document.getElementById("num2").value;
var value = document.getElementById("selection").value;
console.log(value)
if(num1Value === "undefined"){
num1Value = 0;
}
if(num2Value === "undefined"){
num2Value = 0;
}
switch(value){
case "add":
store.dispatch({type:"ADD",num1:num1Value,num2:num2Value})
break
case "minus":
store.dispatch({type:"MINUS",num1:num1Value,num2:num2Value})
break
case "multiply":
store.dispatch({type:"MULTIPLY",num1:num1Value,num2:num2Value})
break
case "divide":
store.dispatch({type:"DIVIDE",num1:num1Value,num2:num2Value})
break
}
}
</script>
</body>
</html>