If I have Rx.Observable, how can I sign up for several functions through it forEach? The code below works, but this part, in particular, is not very dry for me:
Rx.Observable.from(definition).forEach(highlight);
Rx.Observable.from(definition).forEach(prefix);
I know that I can create a wrapper function that calls the two inside it, but I like readability to keep them separate. I would like to do something similar to
Rx.Observable.from(definition).forEach(highlight, prefix)
or
definition = Rx.Observable.from(definition)
definition.forEach(highlight)
definition.forEach(prefix)
or
Rx.Observable.from(definition).forEach(highlight).forEach(prefix)
... but none of them work. What would be the best way to reorganize this?
JS:
(function commands() {
function highlight(node) {
node.classList.add(hoverClass);
}
function unhighlight(node) {
node.classList.remove(hoverClass);
}
function prefix(node) {
node.classList.add(prefixClass);
}
function unprefix(node) {
node.classList.remove(prefixClass);
}
function unprefixAll(nodes) {
Rx.Observable.from(nodes).forEach(unprefix);
}
var hoverClass = "hover";
var prefixClass = "prefixed";
var $commands = document.querySelector("#commands");
var definitions = Rx.Observable.from($commands.querySelectorAll("dt"))
.map(function(_, i) {
return $commands.querySelectorAll(
"dt:nth-of-type("+ (i + 1) +"), dt:nth-of-type("+ (i + 1) +") + dd"
);
});
definitions.forEach(function (definition) {
Rx.Observable.fromEvent(definition, "mouseover").forEach(function() {
definitions.forEach(unprefixAll);
Rx.Observable.from(definition).forEach(highlight);
Rx.Observable.from(definition).forEach(prefix);
});
Rx.Observable.fromEvent(definition, "mouseout").forEach(function() {
Rx.Observable.from(definition).forEach(unhighlight);
});
});
})();
HTML:
<dl id="commands">
<dt class="prefixed">command 1</dt>
<dd>does a thing for command 1</dd>
<dt>command 2</dt>
<dd>does a thing for command 2</dd>
<dt>command 3</dt>
<dd>does a thing for command 3</dd>
<dt>command 4</dt>
<dd>does a thing for command 4</dd>
<dt>help</dt>
<dd>Shows all available commands</dd>
</dl>
source
share