Impact

This forum is read only and just serves as an archive. If you have any questions, please post them on github.com/phoboslab/impact

1 decade ago by Heiko

Hi, would it be feasible to do something like in the code below ? I've got multiple entities/objects that require a callback when image gets loaded. Currently I only get callback for the last object that sets the ig.Image onload callback.

There prob lots of ways to do this - I'm looking for a simple yet functional way to do this, without adding too much code.

Event code below is based on the observer pattern.


ig.module (
	'plugins.extend-image-onload-callback'
)
.requires (
	'impact.impact',
	'impact.image'
)
.defines( function () {
	// --------------------------------------------------------------------------------------------------------------------
	// Event 
	//
	var Event = function(sender) {
		this._sender = sender;
		this._listeners = [];
	}
	
	Event.prototype.addListener = function(listener) {
		for (var i = 0; i < this._listeners.length; i++) {
			if (this._listeners[i] === listener) {
				//console.log('listener already subscribed, no duplicate listeners allowed');
				return false;
			}
		}
		this._listeners.push(listener);
		return true;
	}
	
	Event.prototype.removeListener = function(listener) {
		for (var i = 0; i < this._listeners.length; i++) {
			if (this._listeners[i] === listener) {
				//console.log('found matching listener, idx = ' + i);
				this._listeners.splice(i, 1);
				return true;
			}
		}
		return false;					// no matching listener found
	}
	
	Event.prototype.notify = function(args) {
		for (var i = 0; i < this._listeners.length; i++) {
			this._listeners[i](this._sender, args);
		}
	}
	
	//
	// extend ig.Image to support multiple onload callbacks
	//
	ig.Image.inject({
		onload_callback: null,
		onload_addListener: function(listener) {
			if (!this.onload_callback)
				this.onload_callback = new Event();
			if (this.onload_callback)
				this.onload_callback.addListener(listener);
		},
		onload_removeListener: function(listener) {
			if (this.onload_callback)
				this.onload_callback.removeListener(listener);
			// can add code here to clear callback if no more listeners
		},
		onload: function(event) {
			this.parent(event);
			
			if (this.onload_callback)
				this.onload_callback.notify(/* can add parameters here */);
		}
	});
	
});

I'm looking to do something like this in my Impact-ScaledAlphaHitmask plugin. (see ig.Image.inject.

1 decade ago by Heiko

Using an EventEmitter as an alternative would be another (better, more flexible) option, if used across the whole ig system. But implementing this for just one callback would be a bit of an overkill.
Page 1 of 1
« first « previous next › last »