Introducing MooTools ElementSpy

By  on  

One part of MooTools I love is the ease of implementing events within classes. Just add Events to your Implements array and you can fire events anywhere you want -- these events are extremely helpful. ScrollSpy and many other popular MooTools plugins would be nothing without events. And think of DOM elements without events...terrible! Not knowing when someone clicked, hovered, etc. would completely defeat the purpose of JavaScript!

I wanted to take basic element events further. Sure I know when the value of an input changes (via onChange), but what about when another attribute changes? Or a style change? Or the change in a storage value? ElementSpy allows you to assign periodical checks on element attributes or other aspects of elements.

The MooTools Javscript

var ElementSpy = new Class({
	Implements: [Options,Events],
	options: {
		interval: 100
	},
	initialize: function(element,attribute,options) {
		this.setOptions(options);
		this.element = document.id(element);
		this.val = this.getter(attribute);
		this.interval;
		this.worker = function() {
			var value = this.getter(attribute);
			this.fireEvent('check',[this.val,value]);
			if(value != this.val) {
				this.fireEvent('change',[this.val,value]); //old,new
				this.val = value;
			}
			else {
				this.fireEvent('stagnate',[value]); //current
			}
		}.bind(this);
	},
	start: function() {
		this.interval = this.worker.periodical(this.options.interval);
		this.fireEvent('start');
		return this;
	},
	stop: function() {
		$clear(this.interval);
		this.fireEvent('stop');
		return this;
	},
	getter: function(attribute) {
		return $type(attribute) == 'function' ? (attribute.bind(this.element))() : this.element.get(attribute);
	}
});

The following are arguments, options, and events for ElementSpy:

Arguments

  • element: The element to spy on.
  • attribute: The attribute to spy on *or* a function that returns a value.
  • options: The class options.

Options

  • interval: (defaults to 100) The frequency in milliseconds that the element should be checked.

Events

  • change: Fired when the value has changed.
  • check: Fired every time the element is checked.
  • start: Fired when an element starts being spied on.
  • stop: Fired when you stop spying on an element

The MooTools ElementSpy Usage

var element = document.id('my-image');
/* simple: just watch an attribute */
var spy = new ElementSpy(element,'src', { 
	duration: 200,
	onChange: function(old,nu) { //alert when the image's SRC has changed!
		alert('Image SRC changed from ' + old + ' to ' + nu);
	}
});
//start spying on the image SRC!
spy.start();

This first usage is about as basic as it gets -- listening for an image SRC change.

/* difficult: watch a style */
var element2 = document.id('button2');
var spy2 = new ElementSpy(element2,function() {
	return this.getStyle('cursor');
}, { 
	duration: 200,
	onChange: function(old,nu) {
		alert('Change!  Value changed from [' + old + '] to ' + nu + ']');
	},
	onCheck: function(old,nu) {
		console.log('Check:  Value changed from [' + old + '] to ' + nu + ']');
	}
});
spy2.start();
element2.addEvent('click',function() {
	this.setStyle('cursor','pointer');
	(function() { spy2.stop(); }).delay(2000);
});

This second, more advanced solution listens for a change in CSS cursor and allows me to fire events accordingly.

Please keep in mind that this class can be harsh on the browser if overused so please use with care! I'd also like to hear your thoughts on the class. Like it? Dislike? Have improvement ideas? Let me know!

Recent Features

Incredible Demos

Discussion

  1. there is a typo in the stop options.

    “start: Fired when you stop spying on an element”

    great post (As usually)!

  2. David, this is very useful! Thank you! BTW, It looks like Harald Kirschner’s Observer class, but more functional :) Mootools FTW!!11

  3. Nice idea, David. Do you think this could be combined with native Javascript getter/setters for browsers that support them? I understand getters and setters are not very standard or supported, but it would be cool to use them when possible, right?
    https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Creating_New_Objects/Defining_Getters_and_Setters

  4. Guillermo Rauch

    Nice idea. Not sure if I’d implement it as a standalone Class myself though.

    Also, I would avoid the timer if DOMAttrModified is available:

    if (document.implementation.hasFeature('MutationEvents','2.0')){
      // subscribe to DOMAttrModified
    } else {
      timer
    }
    

    There’re many ways to approach this problem. Another would be to create a custom MooTools event.

  5. Also, another way to detect support is to check for the presence of the MutationEvent constructor

    if (document.implementation.hasFeature(‘MutationEvents’,’2.0′) || ‘MutationEvent’ in window)

  6. This is a sweet plugin, Thanks David !

  7. Sweet plugin, awesome site!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!