bjork24
bjork24

Reputation: 3183

Calling a method function from a jQuery plugin

Give the following jQuery plugin:

(function($) {

  $.fn.prefCookie = function(method) {

    var options = {
      cookieName : 'prefs',
      actionType : 'click',
      key : '',
      value : false
    }

    var $obj;

    var methods = {

      init : function(config) {
        return this.each(function() {
          if(config) { $.extend(options, config) }
          $obj = $(this);
          options.value ? 
            $obj.bind(options.actionType,helpers.setPref) :
            $obj.bind(options.actionType,helpers.togglePref) ;
        });
      },

      anotherFunction : function() {
        console.log('you did it!');
      }

    }

    var helpers = {

      togglePref : function() {

      },

      setPref : function() {

      }

    }

    if (methods[method] && method.toLowerCase() != 'init') {
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
      return methods.init.apply(this, arguments);
    } else {
      $.error( 'Method "' +  method + '" does not exist in the Pref Cookie plugin!');
    }

  }

})(jQuery);

How can anotherFunction without attaching the plugin to anything. I'd like to do $.prefCookie.anotherFunction or something, but it doesn't work. Any suggestions?

Upvotes: 0

Views: 97

Answers (2)

alex
alex

Reputation: 490153

It looks like you have set it up to handle the method call passed in by string.

If you want to do it as you say $.prefCookie.anotherFunction (which is different because there is no jQuery collection associated with it), try something like...

$.fn.prefCookie.anotherFunction = function() { }

jsFiddle.

Upvotes: 0

wsanville
wsanville

Reputation: 37516

$('your selector').prefCookie('anotherFunction'); should do it.

If you need to pass any parameters to anotherFunction, just add them after the string 'anotherFunction'.

Upvotes: 1

Related Questions