Created
July 8, 2018 04:07
-
-
Save thinkgarden/2946da8fbb7e5d3ef7e353b7e2446835 to your computer and use it in GitHub Desktop.
[little saga] some concept for saga
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"></meta> | |
<meta | |
name="viewport" | |
content="width=device-width, initial-scale=1.0" | |
></meta> | |
<meta | |
http-equiv="X-UA-Compatible" | |
content="ie=edge" | |
></meta> | |
<title>Redux Saga Kit</title> | |
</head> | |
<body> | |
<button id="test">Click Me</button> | |
<div id="result"></div> | |
<script> | |
function channel() { | |
let taker; | |
function take(cb) { | |
taker = cb; | |
} | |
function put(input) { | |
if (taker) { | |
const tempTaker = taker; | |
taker = null; | |
tempTaker(input); | |
} | |
} | |
return { | |
put, | |
take, | |
}; | |
} | |
const chan = channel(); | |
function take() { | |
return { | |
type: 'take' | |
}; | |
} | |
function fork(cb) { | |
return { | |
type: 'fork', | |
fn: cb | |
} | |
} | |
function* takeEvery(worker) { | |
yield fork(function* () { | |
while(true) { | |
const action = yield take(); | |
worker(action); | |
} | |
}); | |
} | |
function runTakeEffect(effect, cb) { | |
chan.take(input => { | |
cb(input); | |
}); | |
} | |
function runForkEffect(effect, cb) { | |
task(effect.fn || effect); | |
cb(); | |
} | |
function task(iterator) { | |
const iter = typeof iterator === 'function' ? iterator() : iterator; | |
function next(args) { | |
const result = iter.next(args); | |
console.log('res',result); | |
if(!result.done) { | |
const effect = result.value; | |
if(typeof effect[Symbol.iterator] === 'function') { | |
runForkEffect(effect, next); | |
} else if(effect.type) { | |
switch(effect.type) { | |
case 'take': | |
runTakeEffect(effect, next); | |
break; | |
case 'fork': | |
runForkEffect(effect, next); | |
break; | |
default: | |
} | |
} | |
} | |
} | |
next(); | |
} | |
const $btn = document.querySelector('#test'); | |
const $result = document.querySelector('#result'); | |
function* mainSaga() { | |
const action = yield take(); | |
$result.innerHTML = action; | |
console.log(action); | |
} | |
function* mainSaga1() { | |
yield takeEvery(action => { | |
$result.innerHTML = action; | |
}); | |
} | |
task(mainSaga1); | |
let i = 0; | |
$btn.addEventListener('click', function(){ | |
const action = `action data${i++}`; | |
chan.put(action); | |
}, false); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment