简体   繁体   中英

jQuery Plugin callback doesn't work properly

I replicate the problem in simple plugin in jsfiddle: https://jsfiddle.net/5atn3010/1/

The idea is:

  • I have 2 selectors with a range of years (from 2005 to 2020)
  • When I select an option in the first selector, the selected value (for example 2010) is set in the second selector as the minimum value.
  • Finally the second selector is redrawn and only shows the new values (form 2010 to 2020)

This works, but with a big mistake. Not only changes the second select values, but the minimum value for the first selector also changes.

Why does it happen? How can I solve it?

;(function ( $, window, document, undefined ) {

    "use strict";

    var pluginName = "testing";

    function Plugin( element, options ) {

        this.element = element;
        this.$element = $(element);
        this.name = pluginName;

        this.opts = $.extend({}, $.fn[pluginName].defaults, options);

        this.$elements = {
            year:null,
        }

        this.init(element,options);

    }


    Plugin.prototype =  {

        init: function () {
            var me=this;

            me.$elements.year=$("<select />").attr("name","year");
            if (me.opts.css!=null) {
                me.$elements.year.addClass(me.opts.css);
            }

            me.$elements.year.on("change",function() {
                me.opts.onChange.call(me,me.$elements.year.val());
                me._draw.call(me); //redraw me only for show error
            });

            me.$element.append(me.$elements.year);

            me._draw();
        },

        _draw: function() {
            var me=this;

            var date_start=me.opts.date.start;
            var date_end=me.opts.date.end;

            me.$elements.year.find("option").remove();
            for (var i=date_start;i<=date_end;i++) {
                var option=$("<option/>").attr("value",i).text(i);
                me.$elements.year.append(option);
            }
        },

        setMin: function(min) {
            this.opts.date.start=min;
            this._draw();
        }

    }


    $.fn[pluginName] = function(options) {
        var param=arguments[1];
        return this.each(function() {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
            }
            else if ($.isFunction(Plugin.prototype[options])) {
                $.data(this, 'plugin_' + pluginName)[options](param);
            } else {
                $.error('Method ' + options + ' is not available');
            }
        });
    };

    $.fn[pluginName].defaults = {
        date: {
            start:2005,
            end:2020
        },
        onSelect:function() {}
    };


})( jQuery, window, document );

$().ready(function(){
   $("#span1").testing({
       onChange:function(min) {
           console.log(min);
            $("#span2").testing("setMin",min);
       }
   });
   $("#span2").testing();
});

there are two issues with your code. First of all - you're not extending your options object recursively. To be short - you have two different opts objects that holds a reference to the same date object. I added some logging so you can understand what I'm talking about. You need to deep copy your options object.

Please, read carefully jQuery.extends page http://api.jquery.com/jquery.extend/

Secondly, you assign this.opts.date.start to a <option> value. It works okay for now but it won't work as expected if you will try to set a minimum date to selected date + N . It will concatenate N as a string instead of adding. I added some logs for this case as well.

http://jsfiddle.net/5atn3010/7/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM