2

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*/

}

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.