generalized .length check on functions
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) {
ret开发者_开发技巧urn function(e){
if (!(e.length)) { return false;}
}
}
this.example = function(e) {
ck(e)
/*blablabla*/
}
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.
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.
精彩评论