Skip to content

Instantly share code, notes, and snippets.

@anthonycintron
Created January 5, 2011 17:42
Show Gist options
  • Save anthonycintron/766651 to your computer and use it in GitHub Desktop.
Save anthonycintron/766651 to your computer and use it in GitHub Desktop.
Experimenting with JavaScript's custom event model
function EventDispatcher() {
this._listeners = {};
}
EventDispatcher.prototype = {
constructor: EventDispatcher,
addEventListener: function (type, listener) {
if ( typeof this._listeners[type] == "undefined" ) {
this._listeners[type] = [];
}
this._listeners[type].push(listener);
},
dispatchEvent: function(event) {
if (typeof event == "string"){
event = { type: event };
}
if (!event.target){
event.target = this;
}
if (!event.type){
throw new Error("Event object missing 'type' property.");
}
if (this._listeners[event.type] instanceof Array){
var listeners = this._listeners[event.type];
for (var i=0, len=listeners.length; i < len; i++){
listeners[i].call(this, event);
}
}
}
};
Projects.prototype = new EventDispatcher();
Projects.prototype.constructor = Projects;
function Projects() {
EventDispatcher.call(this);
this._list = [];
};
Projects.prototype.load = function() {
var that = this;
function build_list(data, parent) {
var value = eval(data);
for ( index in value ) {
var project = new Object();
project.name = value[index].fields.name;
project.archived = value[index].fields.archived;
project.visible = value[index].fields.visible;
project.file_path_0 = value[index].fields.file_path_0;
project.file_path_1 = value[index].fields.file_path_1;
project.file_path_2 = value[index].fields.file_path_2;
project.file_path_3 = value[index].fields.file_path_3;
project.file_path_4 = value[index].fields.file_path_4;
project.file_path_5 = value[index].fields.file_path_5;
project.file_path_6 = value[index].fields.file_path_6;
project.file_path_7 = value[index].fields.file_path_7;
project.file_path_8 = value[index].fields.file_path_8;
project.file_path_9 = value[index].fields.file_path_9;
parent._list.push(project);
} // end for
parent.dispatchEvent("data_loaded");
};
$.get("/html/portfolio/", function(data) {
build_list(data, that);
// displatch data loaded event.
});
};
Projects.prototype.get_archives = function() {
_archive = {};
for ( var i = 0; i < this._list.length; i++ ) {
if ( this._list[i].name == "ARCHIVES" ) {
_archive = this._list[i];
}
}
return _archive;
};
Projects.prototype.get_active_projects = function() {
_active_p = [];
for ( var i = 0; i < this._list.length; i++ ) {
if ( this._list[i].visible == true ) {
_active_p.push(this._list[i]);
}
}
return _active_p;
};
// End result
var p = new Projects();
p.load();
p.addEventListener("data_loaded", function(e) {
alert(e.target.get_archives().name);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment