watched.js
Live, event driven dom element collections
watched('.foo').on('changed', function(currentElements){
console.log(currentElements);
});
Installation
NPM
$ npm install watched --save
Bower
$ bower install watched
Download
Download the latest release and use build in /dist
Usage
Load
Node/Browserify
var watched = require('watched');
Browser
<script src="watched.js"></script>
AMD
TODO
watch
The watched nodelists only contain elements that are part of the visual dom. So if you remove
the parent element of, or the watched element itself, the nodelist will be empty.
If once removed element are stored somewhere and are later re-added to the dom, the lists may be filled again.
// give me nodelists // quickvar foos = ; // or more specificvar foos2 = ; // same as watched('.foo')var bars = ;var bazs = ;var links = ; // need the lengthvar linkcount = linkslength; // access elements directly var aLink = links0; // or iteratefoos; // finally, stay up to date, when elements are addednodeList; // removednodeList; // or changed in generalnodeList;
Documentation
You can see the full API docs here: http://grmlin.github.io/watched/
How?
Behind the scenes, watched.js uses the all new MutationObserver
to detect changes in the dom. Browser support is quite good these days.
An interval based fallback is included, so older browsers will profit, too. Anything >= IE9 should be fine.
In either case only a single mutation observer will be created for the scripts lifespan. All LiveNodeList
instances will listen to this one observer.
Important notes
-
Only elements in the visual dom are affected. Whenever an element or it's parent is removed from the dom, it will be removed from the live nodelist
-
The dom mutation listener is debounced! That's why massive changes to the dom will happen in batches, not individually, and take some time. (20ms at the moment)
-
Always use the
added
,removed
andchanged
events! The node lists are live and bound to changes in the dom, but never called synchronously after the dom changed (see debouncing above). -
The fallback is slower than native! It uses an intervall to scan for changes. It's not a good idea to do this too often, so the current timeout is set to 500ms.
-
The magic might become expensive! You better not use hundreds of live nodelists, they will all be updated and the queries re-evaluated in the background, when the dom changes!
Thanks
- DECAF
- smokesignals.js - used as event emitter