Created
July 19, 2013 02:59
-
-
Save sofish/6034790 to your computer and use it in GitHub Desktop.
multiple actions
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> | |
<head> | |
<meta charset="utf-8" /> | |
<title>multiple actions</title> | |
</head> | |
<body> | |
<h4>open the console and click the buttons:</h4> | |
<p><button data-action="action1, action2">hello</button> action1 and action2 will be excuted in sequence.</p> | |
<p><button data-action="action3, action2">world</button> action3 return an undefined, thus, the action2 will not be excuted.</p> | |
<script> | |
var handler, obj; | |
handler = function(e) { | |
var dataset = e.target.dataset | |
, actions = dataset.action.replace(/\s+/g,'').split(','); | |
!dataset.silence && e.preventDefault(); | |
while(actions.length) { | |
// if there's always having an object contains functions like jQuery.fn.x | |
var fn = obj[actions.shift()]; | |
if(typeof fn === 'function' && fn()) continue; | |
// stop the queue when the previous action didn't return true | |
actions.length = 0; | |
} | |
}; | |
obj = { | |
action1: function(){ | |
return console.log('action1 excuted!'), 'helloworld'; | |
}, | |
action2: function(){ | |
console.log('action2, final'); | |
}, | |
action3: function(){ | |
console.log('action3'); | |
} | |
}; | |
[].slice.call(document.querySelectorAll('[data-action]')).forEach(function(item) { | |
item.addEventListener('click', handler); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment