@cubooks
Web-developer

Как вернуть API jQuery-плагина?

Здравствуйте. Не могу сообразить, как вернуть api jquery-плагина.

Кусок кода плагина:
var api = function(element, options) {
      return {...};
}

/**
     * Plugin register
     * @param options
     * @returns {*}
     */
    $.fn.plugin = function (options) {
        return this.each(function (key, value) {
            var element = $(this);

            // Return early if this element already has a plugin instance
            if (element.data('plugin'))
                return element.data('plugin');

            // Pass options to plugin constructor
            var api = new api(this, options);

            // Store plugin object in this element's data
            element.data('plugin', api);

            return api;
        });
    };


Вызываю его вот так:
var myPlug = $('el').plugin(...);
console.log(myPlug); //[div#plugin, context: document, selector: "#plugin"]

myPlug.publicMethod(); //publicMethod, например. Но будет ошибка, т.к при вызове плагина не возвращается его api
  • Вопрос задан
  • 287 просмотров
Решения вопроса 2
miraage
@miraage
Старый прогер
Посмотрите, как люди пишут плагины.
Например, bootstrap tooltip.

// TOOLTIP PLUGIN DEFINITION
  // =========================

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.tooltip')
      var options = typeof option == 'object' && option

      if (!data && /destroy|hide/.test(option)) return
      if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  var old = $.fn.tooltip

  $.fn.tooltip             = Plugin
  $.fn.tooltip.Constructor = Tooltip
Ответ написан
@jekaD
Если нужно возвращать публичные методы лучше использовать такой вариант

(function( $ ){
	
	var methods = {
		
		init: function (options) {
                   var defaults = $.extend( {}, options ) //если передаете аргументы при инициализации
                },
                anotherMethod: function () {
                }
         }
         $.fn.pluginName = function (method) {
		
		if ( methods[method] ) {
				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 + ' не существует в jQuery.pluginName' );
		}
	}
})( jQuery );
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
30 апр. 2024, в 22:44
500 руб./в час
30 апр. 2024, в 21:45
20000 руб./за проект
30 апр. 2024, в 21:36
1500 руб./в час