Я «реализуется» своего рода функциональность копирования вставки в fullcalendar как так:копирования и вставки событие в fullcalendar
- Использование eventRender обратного вызова для привязки правой кнопкой мыши на каждом элементе событий, показывая контекстное меню.
- Он копирует события
- переплетен каждый слот с контекстным меню, чтобы показать функцию вставки
- На пункте меню щелкни я отправляю данные через AJAX (новую дату и время) для события, и вернуть новый json события, чтобы вернуться в календарь.
Зачем так много неприятностей, когда можно сказать, что полный календарь allready имеет возможность редактирования событий. Потому что (если я не ошибаюсь), я хотел, чтобы пользователь мог копировать событие и переносить его на другой день (через 2 или 3 или 4 дня), где он видит открытый слот. Он отлично работает (хотя я должен что-то делать с часовыми поясами и временными разностями, потому что бэкэнд находится в Django, используя TIME_ZONE). Но если я попытаюсь вставить его в другой слот, он просто не будет работать. Вот пример кода (Пожалуйста, не ненавидеть ... мые)
события контекстного меню
eventRender: function (event, element){
element.bind('contextmenu', function(e){
e.preventDefault();
console.log('Right clicking')
showContextualMenu(event, element, e);
});
}
function showContextualMenu(event,element, e){
$("#contextual-menu").css({
'position':'fixed',
'top':e.clientY,
'left':e.clientX
}).fadeIn(500, function(){
$(document).bind("click", function(){
$('#contextual-menu').hide(500);
$(document).off("click");
});
options = $("#contextual-menu ul").children();
options.one('click', function(){
console.log("Inside click");
if ($(this).data('action')=== "move"){
console.log("Inside if");
alert("Copied event to move it");
copiedEvent = event; //Global variable inside on $(document).ready()...note the best implementation I know, but had to pass the event everywhere
paste = true; //paste is a variable telling us that there is an event wating to be pasted elswhere.
}
});
});
}
Я также переплетен слоты повестки дня с контекстным меню, так что пользователь может щелкни правую кнопку мышь в слоте и если в скобке есть копия, чтобы скопировать ее.
//agenda-slots right click menu creation
var slots = $("table.fc-agenda-slots tbody").children();
slots.bind('contextmenu', function (e){
e.preventDefault();
if (paste===true){
showSlotContextualMenu($(this),e);
}
});
function showSlotContextualMenu(slot,e){
$("#contextual-menu2 li").unbind('click');//If user only renders the menu but doesn't click i need to unbind the click method
var hour = parseInt(((slot.first().text()).split(":"))[0]);//hour of the slot
var minutes = parseInt(((slot.first().text()).split(":"))[1]);//minutes of the slot
//start = $("#calendar").fullCalendar('getDate');//date in which i am currently (case i want to paste event on different date)
//start.setHours(hour);
start.setMinutes(minutes);
//end = $("#calendar").fullCalendar('getDate'); not necessary, the sever takes the duration of initial/copied event, and calculates the end time
$("#contextual-menu2").css({
'top':e.pageY,
'left':e.pageX,
'position':'absolute'
}).fadeIn(500, function(){
//user can click anywhere to close menu
$(document).bind("click", function(){
$("#contextual-menu2").hide(500);
$(document).off("click");
});
$("#contextual-menu2 li").one("click", function(){
//binding once every time contextual menu is shown...Dont think its the best way, please if you have advices, would love to hear them.
if (confirm("This will move appointment with title: "+copiedEvent.title+ ". Do you want to proceed?")){
alert("I will save your event");
date = $("#calendar").fullCalendar('getDate');
//ajax call to save event on success event will be placed in this slot and removed from the previous one
$.ajax({
url:"/calendar/entry/move/",
type:"post",
dataType:'json',
data:{
id: copiedEvent.id,
start: copiedEvent.start.toGMTString(),
end: copiedEvent.end.toGMTString(),
color:copiedEvent.color,
csrfmiddlewaretoken:$("input[name='csrfmiddlewaretoken']").val(),
year: date.getFullYear(),//new year
month:date.getMonth(), //new month
day:date.getDate(), new date
hour:hour, //new hour (from slot)
minutes:minutes //new minutes(from slot)
},
success:function (data, status, jqXHR){
alert("Success, You will move "+data.title+" event");
event = copiedEvent;
event.start = data['start'];
event.end = data['end'];
console.log("about to save event"+ event.id+" "+event.start+" "+event.end);
$("#calendar").fullCalendar('renderEvent', event);
paste=false;
copiedEvent=null;
}
});
}
});
});
}
Проблема заключается в том, что, когда я изменить день я например скопировать событие на 18 декабря и идти, чтобы вставить его в разл 20 событие не окажет. Диалоги предупреждений показывают мне, что у них есть правильные данные (дата и т. Д.), Но событие не будет отображаться. Я не сохранил событие в базе данных, я только возвращаю событие в json для тестирования, но он работает, если я не меняю день и вставляю его в тот же день. Не похоже, что что-то не так.