Skip to content

Instantly share code, notes, and snippets.

@keeto
Created December 2, 2009 22:09
Show Gist options
  • Save keeto/247650 to your computer and use it in GitHub Desktop.
Save keeto/247650 to your computer and use it in GitHub Desktop.
Collection Native for MooTools
function Collection(list, build){
this.list = $splat(list || []);
this.length = this.list.length;
this.build = build || true;
if (this.build) this.rebuild();
}
new Native({name: 'Collection', initialize: Collection, generics: false});
(function() {
var proto = Array.prototype;
var destructive = {pop:'remove', push:'add', shift:'remove', unshift:'add', reverse: 'change', splice: 'change'};
// Some browsers don't iterate over natives, so brute force is required.
var natives = ["indexOf", "join", "lastIndexOf", "pop", "push", "reverse", "shift", "slice", "sort", "splice", "unshift"];
natives.each(function(item){
Collection.implement(item, function(){
var destroyed = destructive[item];
if (!!destroyed) this.fireEvent(destroyed, proto.slice.call(arguments))
var results = proto[item].apply(this.list, arguments);
if (!!destroyed) this.clean().rebuild().length = this.list.length;
return results instanceof Array ? new Collection(results) : results;
});
});
/*
for (var i in proto){
if (proto[i] instanceof Function) (function(item){
Collection.implement(i, function(){
this.fireEvent(item, proto.slice.call(arguments));
var results = proto[item].apply(this.list, arguments);
return results instanceof Array ? new Collection(results) : results;
});
})(i);
}
*/
Collection.implement($extend({
toString: function(){
return this.list.toString();
},
valueOf: function(){
return this.list.valueOf();
},
rebuild: function(){
if (!this.build) return this;
for (var x = this.list.length; x--;){
this[x] = this.list[x];
}
return this;
},
clean: function(){
if (!this.build) return this;
for (var i in this){
if (this.hasOwnProperty(i) && (/^([\d])+$/).test(i)) delete this[i];
}
return this;
},
concat: function(){
var args = proto.slice.call(arguments);
args = args.map(function(i){ return i instanceof Collection ? i.list : i; });
var results = proto.concat.apply(this.list, args);
return results instanceof Array ? new Collection(results) : results;
}
}, new Events));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment