开发者

How might you unobtrusively enhance the jQuery Datepicker class?

You can pass special strings into jQuery's Datepicker class setDate() method like "+7" which will be translated into "7 days from today":

http://docs.jquery.com/UI/Datepicker#method-setDate

But you can't get that "+7" back out. When you call getDate() you get the calculated resulting date.

I have a use case where I need to pull out the special string "+7" for propagation. One chunk of code is passing a special string into the Datepicker and passing the Datepicker over to another chunk of code which pulls out the date, but the latter sometimes needs to know the special string rather than the calculated date.

So I need to enhance the Datepicker tool to (a) store the special code internally and (b) expose it via a method like getOriginallyPassedInDate() or some such.

I'm not a jQuery/Javasc开发者_JAVA技巧ript ninja so I could really use some guidance on how I might preferably-unobtrusively add the necessary functionality to the Datepicker class, the way you might monkey-patch an object in Ruby I'm guessing.


Check out Paul Irish's post on Duck Punching with Jquery


this works, based on @petersendidit's suggestion:

// http://paulirish.com/2010/duck-punching-with-jquery/
(function($){
  var _raw = null;
  var _old = $.fn.datepicker;
  $.fn.datepicker = function(arg1, arg2){
    if('getRawDate'==arg1){
      return _raw;
    } else {
      if('setDate'==arg1){
        _raw = arg2;
      }
      return _old.apply(this, arguments);
    }
  };
})(jQuery);


You don't need to Duck Punch or Monkey Patch.

If I use jQuery UI v1.8rc3, then the option to set the default date is defaultDate, not setDate as the documentation indicates. It can be retrieved in the onSelect or onClose fn, like so:

    $('.pick-date').datepicker({
        showWeek: true,
        weekHeader: 'W#',
        defaultDate: "+9",
        onSelect: function(dateText, inst) {
            alert("Select: inst.defaultDate = " + inst.settings.defaultDate);
        },
        onClose: function(dateText, inst) {
            alert("Close: inst.defaultDate = " + inst.settings.defaultDate);
        }
    });

From the Teach-a-man-to-fish department, I did 2 things to learn this:

  1. I looked in the source code for datepicker. It clearly shows a defaultDate option, which is documented to accept a +/-N for offset. It does not have a setDate option.

  2. I ran the page in the debugger, and put a break inside the onClose function. In there I could spelunk the inst parameter, and saw that the settings were stored there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜