开发者

how to run a function every time i call an object

I'm creating a Javascript framework and this is my problem: I have an object and an array. I need to clear the array every time I call the object.

var obj = 
{
 ary : [],
 getById :function(id){  this.ary[ary.length]= document.getElementById(id); return obj; },
 getByNames :function(names){ //loop over the names parameter and get element by names and then add these elements to the array; return obj; },
show :function(){// in here i loop over the array and show elements}

}

All I need to know is how to clear that array every time i recall the obj object

//this works perfectly 
obj.get('id').show();
//but when i recall it again like this in debugger mode i see the array have 2 elements not 1 
obj.get('another id').show();

All I want is to make it so that every time the obj is call开发者_JAVA技巧ed to clear the array.

i need to mention it that i will have a chain in this, i mean like that

obj.getById('').getByNames('');

so i will need the array per chain then clear it in the next call of the object

regards


If by "recall the obj object" you mean return obj; then just find and replace return obj; with this.arr=[]; return obj; to clear the array every time you return obj.

Edit:

ok so you only want to clear the array when you begin a new chain. the only way i can think of is to do something like obj.clr().getById('').getByNames(''); and add clr: function() {this.ary=[]; return this;} to obj


The first line of the function you could do this.arr.length = 0 which will truncate the array so it doesn't have any members.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜