Tutorial :generalized .length check on functions



Question:

When i write a function in JS or jQuery and a parameter is required, i use the if something.length trick...

this.example = function(e) {    if ($(e).length) {      /*blablabla*/    } else {      return false;    }  }  

But i dont want to do this in all functions. Is there a way to generalize this?

like:

this.ck = function(e) {    return function(e){      if (!(e.length)) { return false;}    }  }    this.example = function(e) {       ck(e)      /*blablabla*/    }  


Solution:1

Maybe this, but see below:

function ifNonEmpty(f) {    return function(e) {      if (!$(e).length) return false;      return f(e);    };  }  

You'd use that like this:

var myCoolFunction = ifNonEmpty(function myCoolFunction(e) {    // your implementation  };  

I would however suggest that instead of writing functions that take jQuery objects as parameters, you write those functions as your very own jQuery plugins.


Solution:2

I would suggest the following.

This example would first test whether the parameter actually contains anything (i.e. is not null), then your .length check could be on whether it

function isNonEmpty(p){      if ( (p != null) && (p.length > 0) ){          //test      }  }  

I would be wary of using .length, anyway. For example, if you pass a string .length will have a value!

To test if something is a jQuery object:

alert(p instanceof jQuery); //will alert "true" if p is a jQuery object.  

So, this gives us:

function isNonEmpty(p){      if ( (p != null) && (p instanceof jQuery) && (p.length > 0) ){          //test      }  }  

Or something of that ilk. Either way, there should be sufficient code there to tailor to your intent.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »