There have been a lot of times I have needed some information for a bililiteRange
plugin that was associated with the underlying element, rather than a specific range. For instance, in bililiteRange(element).text('foo')
then bililiteRange(element).undo()
the undo needs to know about the previous text change. jQuery has a data()
method that attaches an object to the element and you can add fields to that object. Actually, it only attaches an index that points to the actual object, since at least in some browsers the garbage collector had trouble with Javascript objects attached to DOM elements and you ended up with memory leaks. I'm not sure if that is still a problem, but it's an easy enough pattern to implement so I used it.
I didn't want to be jQuery-dependent and I wanted to be able to some more sophisticated things with my data, so I implemented my own. At its simplest, just use:
var data = bililiteRange(element).data();
data.foo = 'bar';
assert(bililiteRange(element).data().foo == 'bar');
bililiteRange(element).data()
returns an object that you can add fields to and they will be saved across multiple calls to bililiteRange
.