Вызов функции метода из плагина jQuery - PullRequest
0 голосов
/ 03 ноября 2011

Дайте следующий плагин jQuery:

(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);

Как можно anotherFunction, не подключая плагин ни к чему.Я хотел бы сделать $.prefCookie.anotherFunction или что-то, но это не работает.Есть предложения?

Ответы [ 2 ]

1 голос
/ 03 ноября 2011

$('your selector').prefCookie('anotherFunction'); должен это сделать.

Если вам нужно передать какие-либо параметры в anotherFunction, просто добавьте их после строки 'anotherFunction'.

0 голосов
/ 03 ноября 2011

Похоже, вы настроили его для обработки вызова метода, переданного в виде строки.

Если вы хотите сделать это так, как вы говорите $.prefCookie.anotherFunction (что отличается, потому что с ним не связано ни одно собрание jQuery), попробуйте что-то вроде ...

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

jsFiddle .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...