Search code examples
jqueryjquery-waypoints

Check if method not exist in jQuery plugin


I know how to check if a function or plugin exists, but I am having difficulties this time. Here is my scenario. I've included JQuery Waypoints in my code. Now I want to use $.waypoint('sticky') function, and rightly it gives me error

Error: The sticky method does not exist in jQuery Waypoints. 

I can remove this error by include the sticky shortcut script. Rather I want to check if this method exists, or not.

I tried these, but each of them gives me false even if sticky shortcut script is included.

console.log($.isFunction( $.fn.waypoint.sticky));   //false
console.log($.isFunction( $.fn.waypoint('sticky')));      //false
console.log($.isFunction( $.fn.sticky));      //false

Though this gives me 'true' console.log($.isFunction( $.fn.waypoint));

Any ideas how I can check if the method exists?

EDIT: A bit more clarification: The sticky method does not exist in waypoints plugin by default, and when you include sticky shortcut script, it is included by these lines of code:

$.waypoints('extendFn', 'sticky', function(opt) { .....  }

Solution

  • All methods that exists by default and those added with $.waypoints('extendFn', ... ); are stored inside the plugin in a variable called methods. Its private to the plugin and therefore not accessible from outside without modifying it's source code.

    Each time its called with $.fn.waypoint('methodName') it throws an error if the method doesn't exist or the name is missing. Otherwise it executes the method and returns the jQuery-object, not a function, so the $.isFunction()-test must fail in all cases.

    But you can add a little test-function to the $.waypoints namespace. It does a test-call to $.fn.waypoint and returns true on success. If it fails the thrown error is catched and it returns false:

    jQuery.waypoints.has = function(methodName) {
        try {jQuery.fn.waypoint(methodName)} catch(e) {return false}; return true;
    };
    

    Include it at the beginning of your code but after jQuery Waypoints. Now you can do:

    console.log($.waypoints.has('next')); // --> true
    console.log($.waypoints.has('noExist')); // --> false