From DOM elements
Streams may be created from DOM elements (or every other objects which implements addEventListener
method) by extending hosting object (e.g. document
). You can extend jQuery objects to use stream
with depending on jQuery's on
method.
Actually Warden.js automatically extends jQuery (as constructor) if finds it. So you shouldn't write Warden($('.some-class'))
every time.
Look here to find out more about stream declaring.
Warden(document);
var keydowns = document.stream('keydown');
var clicks = $(document).stream('click');
From custom callback
var keydowns = Warden.Stream(function(emit){
document.addEventListener('keydown', emit);
});
Context
Every stream has context of evaluation. Default context is object itself (e.g. document
for stream made by document.stream("click")
. But you can set context by second argument at method stream
and Warden.Stream
Map
var chars = keydowns
.map('.keyCode')
.map(String.fromCharCode)
Filter
var digits = chars
.filter(function(ch){
return "0123456789".indexOf(ch) != -1;
});
Reduce
var inputs = chars
.reduce('', function(res, ch){
return res.concat(ch);
});
By method bindTo
we set side effects. It means that each time stream gets a value we overwrite some element's innerHTML
property.
document.onreadystatechange = function(){
kd.bindTo(pureDOMElement, 'innerHTML');
chars.bindTo(mappedDOMElement, 'innerHTML');
digits.bindTo(filteredDOMElement, 'innerHTML');
inputs.bindTo(reducedDOMElement, 'innerHTML');
};
//bindTo can be replaced with functions like:
kd.listen(function(value){
pureDOMElement.innerHTML = value;
})