How can I extend jQueryUI datepicker to accept an additional argument?

前端 未结 3 501
悲哀的现实
悲哀的现实 2020-11-30 08:11

I like that jQueryUI datepicker is customizable enough to allow for a button to trigger showing the datepicker, but, unfortunately, it doesn\'t allow you to customize your o

相关标签:
3条回答
  • 2020-11-30 08:37

    How about:

    var __picker = $.fn.datepicker;
    
    $.fn.datepicker = function(options) {
        __picker.apply(this, [options]);
        var $self = this;
    
        if (options && options.trigger) {
            $(options.trigger).bind("click", function () {
                $self.datepicker("show");
            });
        }
    }
    

    Usage:

    $("#date").datepicker({
        trigger: "#button"
    });
    
    $("#date2").datepicker({
        trigger: "#button2"
    });
    

    Example: http://jsfiddle.net/gduhm/


    Or, less intrusively with your own jQuery plugin:

    $.widget("ui.datepicker2", {
        _init: function() {
            var $el = this.element;
            $el.datepicker(this.options);
    
            if (this.options && this.options.trigger) {
                $(this.options.trigger).bind("click", function () {
                    $el.datepicker("show");
                });
            }
        }
    });
    

    (Similar usage, except use datepicker2 or whatever you name it)

    Example: http://jsfiddle.net/puVap/

    0 讨论(0)
  • 2020-11-30 08:43

    You cannot extend because the datepicker does not use the widget factory and thus you can't use it to extend it but you can override the methods and can inject your code. For complete list of methods that Jquery UI Datepicker uses check datepicker.js or jquery-ui.js

    You can simple add that code in your Custom JS file and after overriding you can call datepicker as usual

    $.datepicker._selectDay_old = $.datepicker._selectDay;
    $.datepicker._selectDay = function(id, month, year, td) {
        this._selectDay_old(id, month, year, td);
        // Your code here
        console.log("Injected Custom Method");
    }
    
    // Call Datepicker after Injecting code
    $("#datepicker").datepicker()
    
    0 讨论(0)
  • 2020-11-30 08:44

    Just in case, to define a callable method you must follow this pattern for the method name:

    _<methodName>Datepicker(target, param1, param2,...,paramN)
    

    and if you need to call any internal method that requires a reference to the calendar instance, you must do:

    var inst = this._getInst(target);
    this._internalMethod(inst);
    
    0 讨论(0)
提交回复
热议问题