0

I need a result, like this:

getter

$('selector').myplugin().val();

setter

$('selector').myplugin().val('value');

and i don't want result like this:

$('selector').myplugin({ value: 'value' });

or

$('selector').myplugin('setValue', 'value');

start to define plugin:

(function ($) {
    $.fn.myplugin= function () {
        return this.each(function () {
        var $this = $(this);
        ...
        });
    };
}(jQuery));

this question - How to create a jQuery plugin with methods? not help..

Community
  • 1
  • 1
mathewsun
  • 373
  • 6
  • 14
  • Your use of `val()` in this instance is confusing and you should not be trying to overwrite jquery behaviour imo. The linked question is correct and almost all plugins I have seen work in this way. – jammykam Dec 18 '13 at 06:19
  • 1
    @jammykam thanks. I think i should define plugin - `$('selector').myplugin();` And then set/get value like this - `$('selector').val();`/`$('selector').val("value");` .. – mathewsun Dec 18 '13 at 08:23

1 Answers1

0

This plugin code sets and gets a value in a jQuery plugin.

;(function($) {

    var myValue;

    $.myplugin = {

        myValue: function(value) {

            if (typeof(value) != "undefined") {
                myValue = value;
            } else {
                return myValue;
            }

        }

    }

})(jQuery);


jQuery.myplugin.myValue("test");
alert($.myplugin.myValue());

jQuery.myplugin.myValue(10);
alert($.myplugin.myValue());

Fiddle: http://jsfiddle.net/ypE28/

Bas van Dijk
  • 9,933
  • 10
  • 55
  • 91
  • 1
    Multiple instances of your plugin will share the share `myValue` property. That may be the intention here, but usually it is not. You need to scope the variable. – jammykam Dec 18 '13 at 14:31