Yeah, looks insane, but let me explain better. When in Jquery we use for example $('div') its return an Array Collection or something like this: [div#container, div#header, div#logo], the magic thing is that Methods like push, length, pop, join, concat that are primitive methods from Array will not show you. How can I get this behavior?? I want to return a Collection of Elements just like Jquery does but with my own methods (remove, appendHTML, and others) but not the default Array methods. Any Ideas ??
3 Answers
try creating an object array like this :
var myObjectArray = [];
function addObject(id){
if(document.getElementById(id)!=null){
myObjectArray.push(document.getElementById(id));
return true;
}else{
return false;
}
}
function removeObject(id){
for(i in myObjectArray){
if(myObjectArray[i].getAttribute("id")==id){
delete myObjectArray[i];
return true;
}
}
return false;
}
function getObject(id){
for(i in myObjectArray){
if(myObjectArray[i].getAttribute("id")==id) return myObjectArray[i];
}
return null;
}
-
The Idea is never show the defaults Array Functions (concat, pop, push...) in my likeArray.some(), however when i write likeArray it must show something like ['some','element','another']WSD– WSD03/22/2012 03:27:42Commented Mar 22, 2012 at 3:27
-
Reading in related post i have an Idea... what about this: function <code>likeArray(){ var FINAL = { length:0, splice:function(){ }, add:function (el){ return FINAL[FINAL.length++]=el; }, remove:function(pos){ //my cool stuff to remove } }; return FINAL; }</code>WSD– WSD03/22/2012 03:30:46Commented Mar 22, 2012 at 3:30
You could create a custom object with a private array where you expose the method you want
var yourCollection = function() {
var privateArray = [1, 2, 3, 4];
return {
myCustomPush: function(el) {
//use your custom push function or
privateArray.push(el);
},
size: function() {
return privateArray.length;
}
}
}();
yourCollection.myCustomPush("s");
alert(yourCollection.size());
-
Thanks... but when i write (for example in Firebug console) yourCollection, its show an Object like this: Object { myCustomPush=function(), size=function()}, the idea is show an Array Like Object, like this: ['some','foo','bar'], but when i write yourCollection.some() no methods from native Arrays were showed.WSD– WSD03/22/2012 03:25:39Commented Mar 22, 2012 at 3:25
function() arrayLike {
var FINAL = {
length:0,
splice:function(){}
add:function(el){
return FINAL[FINAL.length++]=el;
};
}
}
Now we can declare a var like this:
var myarray = arrayLike();
myarray.add('some');
myarray.add('other');
And the magic is that we write in Firebug (for example):
myarray.
Only the add() method will show you, but not the defaults Arrays Method (concat, push, pop...) Any Ideas to improve this code, please post It!! or write me (please!)
length
attribute, and assign custom methods toYourArrayLikeObject.prototype
. stackoverflow.com/search?q=jquery+like+array