Search code examples
javascriptcallbackcallapply

Writing Callback functions with preset Parameters


Function :

var Q = {
   each:function(func){
     if(func && typeof func == 'function'){
        var len = this.length;
        for(i=0;i<len;i++){
          this[i];
       }
     }
   }
};

How do I write a callback function in the example above so that the jQuery like function I can do stuff inside the for loop

EX:

 _$('element').each(function(n,i){
       if(i==3){
         _$(this[i]).hide();
       }
 });

and then other instances that can go further into more. I know I can simply write a callback by setting

Function :

var Q = {
   each:function(func){
     if(func && typeof func == 'function'){
        var len = this.length;
        for(i=0;i<len;i++){
          this[i];
          //func(); OR func.call(this,[i,n]);
       }
     }
   }
};

Haven't used apply or call very much and honestly the documentation is a little tricky to understand right now. I believe I wrote my call function correct.


Solution

  • As I've continued practicing I've figured out how to simply write this.

    var Q = {
      each:function(func){
       if(func && typeof func == 'function'){
         var len = this.length;
         for(i=0;i<len;i++){
           func.call(this,i,this[i]);
         }
        }
       }
    };
    

    Which then could be written like

     Q.each(function(i,x){
        if(x.id=="someRandomID" || i = 4){
          this.style.display="none";
        }
    });
    

    I can't give a specific explanation of what the call is doing though I do know using call or apply we preserve the this operator.