Skip to content

Instantly share code, notes, and snippets.

@roodkcab
Last active May 21, 2016 03:34
Show Gist options
  • Select an option

  • Save roodkcab/56a6574c593866379f8e555320dca6f3 to your computer and use it in GitHub Desktop.

Select an option

Save roodkcab/56a6574c593866379f8e555320dca6f3 to your computer and use it in GitHub Desktop.
redux-tag
<!DOCTYPE html>
<html>
<head>
<title>Redux basic example</title>
<script src="https://npmcdn.com/jquery@2.2.4"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script>
<script src="https://npmcdn.com/redux@latest/dist/redux.min.js"></script>
</head>
<body>
<style>
.selected {
background-color: red;
}
span {
border: solid 1px red;
margin: 5px 5px;
}
</style>
<div id="tags" value="你好,再见,1,2,3,4,5,6" select="你好"></div>
<script>
function tagReducer(state, action) {
switch(action.type) {
case '@@INIT': {
let $tags = $("#tags")
let value = $tags.attr("value").split(",")
let selected = ($tags.attr("select") && $tags.attr("select").split(",")) || []
return Immutable.fromJS(value.map(function(elem) {
return Immutable.Map({tag: elem, selected: selected.indexOf(elem) != -1});
}));
break;
}
case 'TAP': {
let index;
index = state.findIndex((item) => item.get('tag') === action.data.tag);
return state
.update(index, (tag) => {
return tag.set('selected', !tag.get('selected'));
});
}
case 'ADD': {
return state
.push(Immutable.Map({
tag: action.data.tag,
selected: true
}));
break;
}
}
}
var store = Redux.createStore(tagReducer, window.devToolsExtension ? window.devToolsExtension() : DevTools.instrument())
function render() {
var $tags = $("#tags")
$tags.html("");
var tags = store.getState().toArray()
var html = []
for (idx in tags) {
let tag = tags[idx]
console.log(tag.get('tag'), tag.get('selected'))
$tag = $("<span>" + tag.get('tag') + "</span>")
if (tag.get('selected')) {
$tag.addClass('selected')
}
$tag.click(function() {
store.dispatch({type: 'TAP', data: {tag: tag.get('tag')}})
});
$tags.append($tag)
}
}
render()
store.subscribe(render)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment