Как создать плагин jQuery с помощью методов?
-
12-09-2019 - |
Вопрос
Я пытаюсь написать плагин jQuery, который предоставит дополнительные функции/методы для объекта, который его вызывает. Все учебные пособия, которые я читаю в Интернете (просматривал последние 2 часа), включают в себя, как самое большее, как добавлять варианты, но не дополнительные функции.
Вот что я хочу сделать:
// Формат div для контейнера сообщения, вызывая плагин для этого Div
$("#mydiv").messagePlugin();
$("#mydiv").messagePlugin().saySomething("hello");
Или что-то вдоль этих линий. Вот что это сводится к: я называю плагин, затем я называю функцию, связанную с этим плагином. Кажется, я не могу найти способ сделать это, и я видел, как многие плагины делают это раньше.
Вот что у меня есть для плагина:
jQuery.fn.messagePlugin = function() {
return this.each(function(){
alert(this);
});
//i tried to do this, but it does not seem to work
jQuery.fn.messagePlugin.saySomething = function(message){
$(this).html(message);
}
};
Как я могу достичь чего -то подобного?
Благодарю вас!
ОБНОВЛЕНИЕ 18 ноября 2013 года: я изменил правильный ответ на ответ Хари следующих комментариев и подсказок.
Решение
Согласно странице авторизации плагинов jQuery (http://docs.jquery.com/plugins/authoring), лучше не задумываться над пространствами имен jQuery и jQuery.fn. Они предлагают этот метод:
(function( $ ){
var methods = {
init : function(options) {
},
show : function( ) { },// IS
hide : function( ) { },// GOOD
update : function( content ) { }// !!!
};
$.fn.tooltip = function(methodOrOptions) {
if ( methods[methodOrOptions] ) {
return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
// Default to "init"
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + methodOrOptions + ' does not exist on jQuery.tooltip' );
}
};
})( jQuery );
По сути, вы храните свои функции в массиве (афератно для функции обертывания) и проверяете запись, если прошел параметр, является строкой, возвращаясь к методу по умолчанию («init» здесь), если параметр является объектом (или нулевым).
Тогда вы можете назвать методы такими, как ...
$('div').tooltip(); // calls the init method
$('div').tooltip({ // calls the init method
foo : 'bar'
});
$('div').tooltip('hide'); // calls the hide method
$('div').tooltip('update', 'This is the new tooltip content!'); // calls the update method
Javascripts «Аргументы» переменная представляет собой массив всех принятых аргументов, поэтому она работает с произвольной длиной параметров функции.
Другие советы
Вот шаблон, который я использовал для создания плагинов с помощью дополнительных методов. Вы бы использовали это как:
$('selector').myplugin( { key: 'value' } );
Или, чтобы привлечь метод напрямую,
$('selector').myplugin( 'mymethod1', 'argument' );
Пример:
;(function($) {
$.fn.extend({
myplugin: function(options,arg) {
if (options && typeof(options) == 'object') {
options = $.extend( {}, $.myplugin.defaults, options );
}
// this creates a plugin for each element in
// the selector or runs the function once per
// selector. To have it do so for just the
// first element (once), return false after
// creating the plugin to stop the each iteration
this.each(function() {
new $.myplugin(this, options, arg );
});
return;
}
});
$.myplugin = function( elem, options, arg ) {
if (options && typeof(options) == 'string') {
if (options == 'mymethod1') {
myplugin_method1( arg );
}
else if (options == 'mymethod2') {
myplugin_method2( arg );
}
return;
}
...normal plugin actions...
function myplugin_method1(arg)
{
...do method1 with this and arg
}
function myplugin_method2(arg)
{
...do method2 with this and arg
}
};
$.myplugin.defaults = {
...
};
})(jQuery);
Как насчет этого подхода:
jQuery.fn.messagePlugin = function(){
var selectedObjects = this;
return {
saySomething : function(message){
$(selectedObjects).each(function(){
$(this).html(message);
});
return selectedObjects; // Preserve the jQuery chainability
},
anotherAction : function(){
//...
return selectedObjects;
}
};
}
// Usage:
$('p').messagePlugin().saySomething('I am a Paragraph').css('color', 'red');
Выбранные объекты хранятся в закрытии MessagePlugin, и эта функция возвращает объект, который содержит функции, связанные с плагином, в каждой функции вы можете выполнять желаемые действия для выбранных в данный момент объектов.
Вы можете протестировать и играть с кодом здесь.
Редактировать: Обновленный код для сохранения мощности цепности jQuery.
Проблема с выбранным в настоящее время ответом заключается в том, что вы на самом деле не создаете новый экземпляр пользовательского плагина для каждого элемента в селекторе, как вы думаете, вы делаете ... вы на самом деле создаете только один экземпляр и проходите в Сам селектор как область прицела.
Вид эта скрипка Для более глубокого объяснения.
Вместо этого вам нужно пройти через селектор, используя jQuery.each и создайте создание нового экземпляра пользовательского плагина для каждого элемента в селекторе.
Вот как:
(function($) {
var CustomPlugin = function($el, options) {
this._defaults = {
randomizer: Math.random()
};
this._options = $.extend(true, {}, this._defaults, options);
this.options = function(options) {
return (options) ?
$.extend(true, this._options, options) :
this._options;
};
this.move = function() {
$el.css('margin-left', this._options.randomizer * 100);
};
};
$.fn.customPlugin = function(methodOrOptions) {
var method = (typeof methodOrOptions === 'string') ? methodOrOptions : undefined;
if (method) {
var customPlugins = [];
function getCustomPlugin() {
var $el = $(this);
var customPlugin = $el.data('customPlugin');
customPlugins.push(customPlugin);
}
this.each(getCustomPlugin);
var args = (arguments.length > 1) ? Array.prototype.slice.call(arguments, 1) : undefined;
var results = [];
function applyMethod(index) {
var customPlugin = customPlugins[index];
if (!customPlugin) {
console.warn('$.customPlugin not instantiated yet');
console.info(this);
results.push(undefined);
return;
}
if (typeof customPlugin[method] === 'function') {
var result = customPlugin[method].apply(customPlugin, args);
results.push(result);
} else {
console.warn('Method \'' + method + '\' not defined in $.customPlugin');
}
}
this.each(applyMethod);
return (results.length > 1) ? results : results[0];
} else {
var options = (typeof methodOrOptions === 'object') ? methodOrOptions : undefined;
function init() {
var $el = $(this);
var customPlugin = new CustomPlugin($el, options);
$el.data('customPlugin', customPlugin);
}
return this.each(init);
}
};
})(jQuery);
Вы заметите, как в первой скрипке все DOV всегда перемещаются вправо на то же количество пикселей. Это потому, что только один Объект параметров существует для всех элементов в селекторе.
Используя методику, написанную выше, вы заметите, что во второй скрипке каждый Div не выровнен и случайным образом перемещается (за исключением первого Div, поскольку его рандомизатор всегда устанавливается на 1 в строке 89). Это потому, что теперь мы правильно создаем новый экземпляр плагина для каждого элемента в селекторе. Каждый элемент имеет свой собственный объект параметров и не сохранен в селекторе, но в случае самого пользовательского плагина.
Это означает, что вы сможете получить доступ к методам пользовательского плагина, созданного на определенном элементе в DOM от новых селекторов JQUERY, и не вынуждены к их кэшировать, как вы находитесь в первой скрипке.
Например, это вернет массив всех объектов параметров, используя технику во второй скрипке. Это вернет неопределенным в первом.
$('div').customPlugin();
$('div').customPlugin('options'); // would return an array of all options objects
Вот как вам придется получить доступ к объекту параметров в первой скрипке, и вернуть только один объект, а не массив из них:
var divs = $('div').customPlugin();
divs.customPlugin('options'); // would return a single options object
$('div').customPlugin('options');
// would return undefined, since it's not a cached selector
Я бы посоветовал использовать приведенную выше технику, а не тот из выбранного в настоящее время ответа.
jQuery сделал это намного проще с внедрением Фабрика виджетов.
Пример:
$.widget( "myNamespace.myPlugin", {
options: {
// Default options
},
_create: function() {
// Initialization logic here
},
// Create a public method.
myPublicMethod: function( argument ) {
// ...
},
// Create a private method.
_myPrivateMethod: function( argument ) {
// ...
}
});
Инициализация:
$('#my-element').myPlugin();
$('#my-element').myPlugin( {defaultValue:10} );
Метод вызов:
$('#my-element').myPlugin('myPublicMethod', 20);
(Вот как jQuery UI Библиотека построена.)
Более простым подходом является использование вложенных функций. Тогда вы можете цепорить их объектно-ориентированным образом. Пример:
jQuery.fn.MyPlugin = function()
{
var _this = this;
var a = 1;
jQuery.fn.MyPlugin.DoSomething = function()
{
var b = a;
var c = 2;
jQuery.fn.MyPlugin.DoSomething.DoEvenMore = function()
{
var d = a;
var e = c;
var f = 3;
return _this;
};
return _this;
};
return this;
};
И вот как это назвать:
var pluginContainer = $("#divSomeContainer");
pluginContainer.MyPlugin();
pluginContainer.MyPlugin.DoSomething();
pluginContainer.MyPlugin.DoSomething.DoEvenMore();
Будьте осторожны, хотя. Вы не можете назвать вложенную функцию, пока она не будет создана. Итак, вы не можете сделать это:
var pluginContainer = $("#divSomeContainer");
pluginContainer.MyPlugin();
pluginContainer.MyPlugin.DoSomething.DoEvenMore();
pluginContainer.MyPlugin.DoSomething();
Функция Doevenmore даже не существует, потому что функция Dosomething еще не выполнялась, что требуется для создания функции Doevenmore. Для большинства плагинов jQuery у вас действительно будет только один уровень вложенных функций, а не два, как я здесь показал.
Просто убедитесь, что когда вы создаете вложенные функции, которые вы определяете эти функции в начале их родительской функции, прежде чем будет выполнено любой другой код в родительской функции.
Наконец, обратите внимание, что «этот» участник хранится в переменной, называемой «_this». Для вложенных функций вы должны вернуть «_this», если вам нужна ссылка на экземпляр в вызывающем клиенте. Вы не можете просто вернуть «это» в вложенной функции, потому что это вернет ссылку на функцию, а не на экземпляр JQuery. Возвращение ссылки на jQuery позволяет цепно внутренним методам jQuery при возврате.
Я получил это от GQUERY PLUGIN PLAOTERPLATE
Также описан в плагин jquery boilerplate, реприза
// jQuery Plugin Boilerplate
// A boilerplate for jumpstarting jQuery plugins development
// version 1.1, May 14th, 2011
// by Stefan Gabos
// remember to change every instance of "pluginName" to the name of your plugin!
(function($) {
// here we go!
$.pluginName = function(element, options) {
// plugin's default options
// this is private property and is accessible only from inside the plugin
var defaults = {
foo: 'bar',
// if your plugin is event-driven, you may provide callback capabilities
// for its events. execute these functions before or after events of your
// plugin, so that users may customize those particular events without
// changing the plugin's code
onFoo: function() {}
}
// to avoid confusions, use "plugin" to reference the
// current instance of the object
var plugin = this;
// this will hold the merged default, and user-provided options
// plugin's properties will be available through this object like:
// plugin.settings.propertyName from inside the plugin or
// element.data('pluginName').settings.propertyName from outside the plugin,
// where "element" is the element the plugin is attached to;
plugin.settings = {}
var $element = $(element), // reference to the jQuery version of DOM element
element = element; // reference to the actual DOM element
// the "constructor" method that gets called when the object is created
plugin.init = function() {
// the plugin's final properties are the merged default and
// user-provided options (if any)
plugin.settings = $.extend({}, defaults, options);
// code goes here
}
// public methods
// these methods can be called like:
// plugin.methodName(arg1, arg2, ... argn) from inside the plugin or
// element.data('pluginName').publicMethod(arg1, arg2, ... argn) from outside
// the plugin, where "element" is the element the plugin is attached to;
// a public method. for demonstration purposes only - remove it!
plugin.foo_public_method = function() {
// code goes here
}
// private methods
// these methods can be called only from inside the plugin like:
// methodName(arg1, arg2, ... argn)
// a private method. for demonstration purposes only - remove it!
var foo_private_method = function() {
// code goes here
}
// fire up the plugin!
// call the "constructor" method
plugin.init();
}
// add the plugin to the jQuery.fn object
$.fn.pluginName = function(options) {
// iterate through the DOM elements we are attaching the plugin to
return this.each(function() {
// if plugin has not already been attached to the element
if (undefined == $(this).data('pluginName')) {
// create a new instance of the plugin
// pass the DOM element and the user-provided options as arguments
var plugin = new $.pluginName(this, options);
// in the jQuery version of the element
// store a reference to the plugin object
// you can later access the plugin and its methods and properties like
// element.data('pluginName').publicMethod(arg1, arg2, ... argn) or
// element.data('pluginName').settings.propertyName
$(this).data('pluginName', plugin);
}
});
}
})(jQuery);
Слишком поздно, но, возможно, это может помочь кому -то однажды.
Я был в такой же ситуации, как, создавая плагин jQuery с некоторыми методами, и после прочтения некоторых статей и некоторых шин я создаю плагин jQuery Pluger Plagin (Cowerplate (https://github.com/acanimal/jquery-plugin-boilerplate).
Кроме того, я разрабатываю с ним плагин для управления тегами (https://github.com/acanimal/tagger.js) и написал два сообщения в блоге, объясняющие шаг за шагом, создание плагина jQuery (http://acuriousanimal.com/blog/2013/01/15/things-i-learned-creating-ajquery-plugin-part-i//).
Ты можешь сделать:
(function ($) {
var YourPlugin = function (element, option) {
var defaults = {
//default value
}
this.option = $.extend({}, defaults, option);
this.$element = $(element);
this.init();
}
YourPlugin.prototype = {
init: function () {
},
show: function() {
},
//another functions
}
$.fn.yourPlugin = function (option) {
var arg = arguments,
options = typeof option == 'object' && option;;
return this.each(function () {
var $this = $(this),
data = $this.data('yourPlugin');
if (!data) $this.data('yourPlugin', (data = new YourPlugin(this, options)));
if (typeof option === 'string') {
if (arg.length > 1) {
data[option].apply(data, Array.prototype.slice.call(arg, 1));
} else {
data[option]();
}
}
});
};
});
Таким образом, ваш объект плагинов хранится как значение данных в вашем элементе.
//Initialization without option
$('#myId').yourPlugin();
//Initialization with option
$('#myId').yourPlugin({
//your option
});
//call show method
$('#myId').yourPlugin('show');
Как насчет использования триггеров? Кто -нибудь знает какой -либо недостаток, используя их? Преимущество заключается в том, что все внутренние переменные доступны через триггеры, а код очень прост.
Смотрите на jsfiddle.
Пример использования
<div id="mydiv">This is the message container...</div>
<script>
var mp = $("#mydiv").messagePlugin();
// the plugin returns the element it is called on
mp.trigger("messagePlugin.saySomething", "hello");
// so defining the mp variable is not needed...
$("#mydiv").trigger("messagePlugin.repeatLastMessage");
</script>
Плагин
jQuery.fn.messagePlugin = function() {
return this.each(function() {
var lastmessage,
$this = $(this);
$this.on('messagePlugin.saySomething', function(e, message) {
lastmessage = message;
saySomething(message);
});
$this.on('messagePlugin.repeatLastMessage', function(e) {
repeatLastMessage();
});
function saySomething(message) {
$this.html("<p>" + message + "</p>");
}
function repeatLastMessage() {
$this.append('<p>Last message was: ' + lastmessage + '</p>');
}
});
}
Здесь я хочу предложить шаги для создания простого плагина с аргументами.
JS
(function($) {
$.fn.myFirstPlugin = function( options ) {
// Default params
var params = $.extend({
text : 'Default Title',
fontsize : 10,
}, options);
return $(this).text(params.text);
}
}(jQuery));
Здесь мы добавили объект по умолчанию под названием params
и установить значения по умолчанию параметров с использованием extend
функция Следовательно, если мы передаем пустой аргумент, он установит значения по умолчанию, а не установит.
HTML
$('.cls-title').myFirstPlugin({ text : 'Argument Title' });
Читать далее: Как создать плагин jQuery
Попробуй это:
$.fn.extend({
"calendar":function(){
console.log(this);
var methods = {
"add":function(){console.log("add"); return this;},
"init":function(){console.log("init"); return this;},
"sample":function(){console.log("sample"); return this;}
};
methods.init(); // you can call any method inside
return methods;
}});
$.fn.calendar() // caller or
$.fn.calendar().sample().add().sample() ......; // call methods
Вот моя версия этого голых костей. Похоже на опубликованные ранее, вы бы назвали:
$('#myDiv').MessagePlugin({ yourSettings: 'here' })
.MessagePlugin('saySomething','Hello World!');
-или доступ к экземпляру напрямую @ plugin_MessagePlugin
$elem = $('#myDiv').MessagePlugin();
var instance = $elem.data('plugin_MessagePlugin');
instance.saySomething('Hello World!');
MessagePlugin.js
;(function($){
function MessagePlugin(element,settings){ // The Plugin
this.$elem = element;
this._settings = settings;
this.settings = $.extend(this._default,settings);
}
MessagePlugin.prototype = { // The Plugin prototype
_default: {
message: 'Generic message'
},
initialize: function(){},
saySomething: function(message){
message = message || this._default.message;
return this.$elem.html(message);
}
};
$.fn.MessagePlugin = function(settings){ // The Plugin call
var instance = this.data('plugin_MessagePlugin'); // Get instance
if(instance===undefined){ // Do instantiate if undefined
settings = settings || {};
this.data('plugin_MessagePlugin',new MessagePlugin(this,settings));
return this;
}
if($.isFunction(MessagePlugin.prototype[settings])){ // Call method if argument is name of method
var args = Array.prototype.slice.call(arguments); // Get the arguments as Array
args.shift(); // Remove first argument (name of method)
return MessagePlugin.prototype[settings].apply(instance, args); // Call the method
}
// Do error handling
return this;
}
})(jQuery);
Это на самом деле можно сделать, чтобы работать «красивым», используя defineProperty
. Анкет Где "хороший" означает без необходимости использовать ()
Чтобы получить пространство имен плагинов или необходимость передавать имя функции по строке.
Совместимость NIT: defineProperty
Не работает в древних браузерах, таких как IE8 и ниже.Предостережение: $.fn.color.blue.apply(foo, args)
Не сработает, вам нужно использовать foo.color.blue.apply(foo, args)
.
function $_color(color)
{
return this.css('color', color);
}
function $_color_blue()
{
return this.css('color', 'blue');
}
Object.defineProperty($.fn, 'color',
{
enumerable: true,
get: function()
{
var self = this;
var ret = function() { return $_color.apply(self, arguments); }
ret.blue = function() { return $_color_blue.apply(self, arguments); }
return ret;
}
});
$('#foo').color('#f00');
$('#bar').color.blue();
Согласно jQuery Standard, вы можете создать плагин следующим образом:
(function($) {
//methods starts here....
var methods = {
init : function(method,options) {
this.loadKeywords.settings = $.extend({}, this.loadKeywords.defaults, options);
methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
$loadkeywordbase=$(this);
},
show : function() {
//your code here.................
},
getData : function() {
//your code here.................
}
} // do not put semi colon here otherwise it will not work in ie7
//end of methods
//main plugin function starts here...
$.fn.loadKeywords = function(options,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 ' + method + ' does not ecw-Keywords');
}
};
$.fn.loadKeywords.defaults = {
keyName: 'Messages',
Options: '1',
callback: '',
};
$.fn.loadKeywords.settings = {};
//end of plugin keyword function.
})(jQuery);
Как назвать этот плагин?
1.$('your element').loadKeywords('show',{'callback':callbackdata,'keyName':'myKey'}); // show() will be called
Ссылка: ссылка на сайт
Я думаю, что это может вам помочь ...
(function ( $ ) {
$.fn.highlight = function( options ) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
color: "#000",
backgroundColor: "yellow"
}, options );
// Highlight the collection based on the settings variable.
return this.css({
color: settings.color,
backgroundColor: settings.backgroundColor
});
};
}( jQuery ));
В приведенном выше примере я создал простой jQuery выделять плагин. Я поделился статьей, в которой я обсуждал Как создать свой собственный плагин jQuery от базового до продвижения. Я думаю, ты должен проверить это ... http://mycodingtricks.com/jquery/how-to-create-your-own-jquery-plugin/
Ниже приведен небольшой плагин, чтобы иметь метод предупреждения для отладки. Сохранить этот код в файле jquery.debug.js: JS:
jQuery.fn.warning = function() {
return this.each(function() {
alert('Tag Name:"' + $(this).prop("tagName") + '".');
});
};
HTML:
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src = "jquery.debug.js" type = "text/javascript"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("div").warning();
$("p").warning();
});
</script>
</head>
<body>
<p>This is paragraph</p>
<div>This is division</div>
</body>
</html>
Вот как я это делаю:
(function ( $ ) {
$.fn.gridview = function( options ) {
..........
..........
var factory = new htmlFactory();
factory.header(...);
........
};
}( jQuery ));
var htmlFactory = function(){
//header
this.header = function(object){
console.log(object);
}
}
Следующая структура плагина использует jQuery-data()
-метод Чтобы обеспечить публичный интерфейс для внутренних плагин-методов/установки (при сохранении цепочки jQuery):
(function($, window, undefined) {
$.fn.myPlugin = function(options) {
// settings, e.g.:
var settings = $.extend({
elementId: null,
shape: "square",
color: "aqua",
borderWidth: "10px",
borderColor: "DarkGray"
}, options);
// private methods, e.g.:
var setBorder = function(color, width) {
settings.borderColor = color;
settings.borderWidth = width;
drawShape();
};
var drawShape = function() {
$('#' + settings.elementId).attr('class', settings.shape + " " + "center");
$('#' + settings.elementId).css({
'background-color': settings.color,
'border': settings.borderWidth + ' solid ' + settings.borderColor
});
$('#' + settings.elementId).html(settings.color + " " + settings.shape);
};
return this.each(function() { // jQuery chainability
// set stuff on ini, e.g.:
settings.elementId = $(this).attr('id');
drawShape();
// PUBLIC INTERFACE
// gives us stuff like:
//
// $("#...").data('myPlugin').myPublicPluginMethod();
//
var myPlugin = {
element: $(this),
// access private plugin methods, e.g.:
setBorder: function(color, width) {
setBorder(color, width);
return this.element; // To ensure jQuery chainability
},
// access plugin settings, e.g.:
color: function() {
return settings.color;
},
// access setting "shape"
shape: function() {
return settings.shape;
},
// inspect settings
inspectSettings: function() {
msg = "inspecting settings for element '" + settings.elementId + "':";
msg += "\n--- shape: '" + settings.shape + "'";
msg += "\n--- color: '" + settings.color + "'";
msg += "\n--- border: '" + settings.borderWidth + ' solid ' + settings.borderColor + "'";
return msg;
},
// do stuff on element, e.g.:
change: function(shape, color) {
settings.shape = shape;
settings.color = color;
drawShape();
return this.element; // To ensure jQuery chainability
}
};
$(this).data("myPlugin", myPlugin);
}); // return this.each
}; // myPlugin
}(jQuery));
Теперь вы можете вызвать внутренние методы плагина для доступа или изменения данных плагина или соответствующего элемента, используя этот синтаксис:
$("#...").data('myPlugin').myPublicPluginMethod();
Пока вы возвращаете текущий элемент (это) из вашей реализации myPublicPluginMethod()
jquery -цепь будет сохранена - поэтому следующие работы:
$("#...").data('myPlugin').myPublicPluginMethod().css("color", "red").html("....");
Вот несколько примеров (для получения подробной информации. Проверьте это скрипка):
// initialize plugin on elements, e.g.:
$("#shape1").myPlugin({shape: 'square', color: 'blue', borderColor: 'SteelBlue'});
$("#shape2").myPlugin({shape: 'rectangle', color: 'red', borderColor: '#ff4d4d'});
$("#shape3").myPlugin({shape: 'circle', color: 'green', borderColor: 'LimeGreen'});
// calling plugin methods to read element specific plugin settings:
console.log($("#shape1").data('myPlugin').inspectSettings());
console.log($("#shape2").data('myPlugin').inspectSettings());
console.log($("#shape3").data('myPlugin').inspectSettings());
// calling plugin methods to modify elements, e.g.:
// (OMG! And they are chainable too!)
$("#shape1").data('myPlugin').change("circle", "green").fadeOut(2000).fadeIn(2000);
$("#shape1").data('myPlugin').setBorder('LimeGreen', '30px');
$("#shape2").data('myPlugin').change("rectangle", "red");
$("#shape2").data('myPlugin').setBorder('#ff4d4d', '40px').css({
'width': '350px',
'font-size': '2em'
}).slideUp(2000).slideDown(2000);
$("#shape3").data('myPlugin').change("square", "blue").fadeOut(2000).fadeIn(2000);
$("#shape3").data('myPlugin').setBorder('SteelBlue', '30px');
// etc. ...
То, что вы сделали, в основном расширяется jquery.fn.messageplugin объект новым методом. Что полезно, но не в вашем случае.
Вы должны сделать это использовать эту технику
function methodA(args){ this // refers to object... }
function saySomething(message){ this.html(message); to first function }
jQuery.fn.messagePlugin = function(opts) {
if(opts=='methodA') methodA.call(this);
if(opts=='saySomething') saySomething.call(this, arguments[0]); // arguments is an array of passed parameters
return this.each(function(){
alert(this);
});
};
Но вы можете выполнить то, что вы хотите, я имею в виду, что есть способ сделать $ ("#mydiv"). MessagePlugin (). Говорит что -то («Привет»); Мой друг, он начал писать о Лугинсе и о том, как расширить их с помощью своей цепочки функциональных возможностей здесь - это ссылка на его блог