JQuery UI Datepicker с JQuery типсы - PullRequest
       14

JQuery UI Datepicker с JQuery типсы

7 голосов
/ 20 февраля 2010

Есть идеи, как реализовать tipsy всплывающих подсказок через пользовательский интерфейс jQuery Datepicker? По сути, я хочу получить всплывающую подсказку, когда пользователь перемещается на определенную дату в DatePicker. Datepicker будет отображаться встроенным и всегда видимым.

Спасибо!

1 Ответ

5 голосов
/ 20 февраля 2010

Звучит круто,

Вот мое решение. Прочитайте комментарии.

(function($){


/** 
 * Returns a dictionary, where the keys are the day of the month, 
 * and the value is the text.
 * @param year - The year of the events.
 * @param month - The month of the events.
 * @param calendarID - Events for a specific calendar.
 */
function getMonthEvents(year, month, calendarId){
  return {11: "My birthday.", 23: "My anniversary" };
}

// Receives January->1
function addTipsys(year, month, calendarId){
   var theEvents = getMonthEvents(year, month, calendarId);
   var theDateLinks = $('#' + calendarId + ' .ui-datepicker-calendar a');
   for(eventDay in theEvents){
      // Minus one, because the date in the tipies are regular dates (1-31)
      // and the links are 0-based.
      theDateLinks.eq(eventDay-1)  // select the right link
         .attr('original-title', theEvents[eventDay])  // set the text
         .tipsy();   // init the tipsy, set your properties.
   }
}

// Because the the event `onChangeMonthYear` get's called before updating 
// the items, we'll add our code after the elements get rebuilt. We will hook 
// to the `_updateDatepicker` method in the `Datepicker`.
// Saves the original function.
var _updateDatepicker_o = $.datepicker._updateDatepicker;
// Replaces the function.
$.datepicker._updateDatepicker = function(inst){ 
   // First we call the original function from the appropiate context.
   _updateDatepicker_o.apply(this, [inst]); 
   // No we can update the Tipsys.
   addTipsys(inst.drawYear, inst.drawMonth+1, inst.id);
};

// Finally the calendar initializer.
$(function(){
   // Creates the date picker, with your options.
   $("#datepicker").datepicker();
   // Gets the date and initializes the first round of tipsies.
   var currentDate = $('#datepicker').datepicker('getDate');
   // month+1 because the event considers January->1
   // Last element is null, because, it doesn't actualy get used in the hanlder.
   addTipsys(currentDate.getYear(), currentDate.getMonth()+1, 'datepicker');
});

})(jQuery);

Неудобства:

  1. Метод get _updateDatepicker вызывается также, когда пользователь выбирает день из видимого месяца, или когда вы устанавливаете дату с помощью datepicker('setDate', theDate), что может быть немного неэффективно.

  2. Он опирается на частную функцию Datepicker, и если в будущих версиях они решат изменить его функциональность или изменить имя, этот код сломается. Хотя из-за характера функции я не вижу, что это произойдет в ближайшее время.

Примечание: Мой первый подход состоял в том, чтобы подключиться к событию onChangeMonthYear ui.datepicker, но поскольку событие инициируется, перед заменой дат в календаре метод addTipsys добавит чаевые к календарным датам, которые собираются очиститься. Поэтому необходимо вызывать событие addTipsys ПОСЛЕ обновления элементов.

EASY HACK: Подключите метод к событию onChangeMonthYear вашего календаря и сделайте setTimeout для вызова подсказок. Некоторая проверка должна быть сделана.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...