javascript 从日历中删除选定的事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10183667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:56:49  来源:igfitidea点击:

Remove selected event from the Calendar

javascriptjqueryspring-mvcfullcalendarfreemarker

提问by Echo

I am using JQuery Full Calendar along with Spring MVC.

我正在使用 JQuery 完整日历和 Spring MVC。

Hello, I have made a demo like that.

你好,我已经像一个演示

Target: I need when the user clicks on an event s/he already inserted,a dialog box appears and gives him/her the capability to either remove that event or cancel.

目标:我需要当用户单击他/她已经插入的事件时,会出现一个对话框,让他/她能够删除该事件或取消该事件。

Issue: Now whenever the user clicks on any day, a dialog appears to allow the user to enter title for that event then user clicks "Ok" to save that event.

问题:现在每当用户在任何一天单击时,都会出现一个对话框,允许用户输入该事件的标题,然后用户单击“确定”以保存该事件。

Freemarker: Freemarker:

自由标记: 自由标记:

<script type="text/javascript">
    var resourceVacation;

    function censor(censor) {
        return (function() {
            var i = 0;
            return function(key, value) {
                if (i !== 0 && typeof(censor) === 'object' && typeof(value) == 'object' && censor == value)
                    return '[Circular]';                   

                ++i; // so we know we aren't using the original object anymore

                return value;
            }
        })(censor);
    }


    function doAjax() {

        $.each(resourceVacation, function(index) {
            var tmpDate = resourceVacation[index].start;
            tmpDate.setHours(tmpDate.getHours() - tmpDate.getTimezoneOffset() / 60);
            resourceVacation[index].start=tmpDate;

        });
//        var arrays = [
//            {"id":111,"title":"event1","start":"2012-04-15T22:00:00.000Z","url":"http://yahoo.com/"}
//        ];
//        var objects = {"id":111,"title":"event2","start":"2012-04-16T22:00:00.000Z","url":"http://yahoo2.com/"};
//
//        arrays.push(objects);
        var test = JSON.stringify(resourceVacation, censor(resourceVacation));
        var x = test;
        $.ajax(
        {
            url:"[@spring.url '/vacation/saveResourceVacation'/]",
            type: "POST",
            data :x ,
            dataType: "json",
            contentType: "application/json"
        });
    }


    $(document).ready(function() {

        var date = new Date();
        var d = date.getDate();
        var m = date.getMonth();
        var y = date.getFullYear();
        $.getJSON('[@spring.url '/vacation/loadResourceVacation'/]', function (data) {
            var calendar = $('#calendar').fullCalendar({
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,agendaWeek,agendaDay'
                },
                selectable: true,
                selectHelper: true,
                select:
                        function(start, end, allDay) {
                            var title = prompt('Event Title:');

                            if (title) {
                                start.setHours(start.getHours() - start.getTimezoneOffset() / 60);
//                                var dat=$.fullCalendar.formatDate( start, "yyyy/MM/dd")


                                var newVacation= {id:133,title:'title',start:start,url: 'title'};
                                resourceVacation.push(newVacation);
                                calendar.fullCalendar('renderEvent',
                                {
                                    title: title,
                                    start: start,
                                    end: end,
                                    allDay: allDay
                                },
                                        true // make the event "stick"
                                        );
                            }
                            calendar.fullCalendar('unselect');
                        },
         eventClick: function(calEvent, jsEvent, view) {

            alert('Event: ' + calEvent.title);
            alert('start: ' + calEvent.start);             
        }

                editable: true,
                events:data
            });
            resourceVacation = data;
        });
    });


</script>

Controller:

控制器:

     @RequestMapping(value = "/vacation/loadResourceVacation", method = RequestMethod.GET)
        public
        @ResponseBody
        String loadResourceVacation(HttpServletResponse response) throws Exception {


            //Here I build my vacationFormBean
            List<VacationFormBean> vacationFormBeanList= buildVacationFormBean();
            // Convert to JSON string.
            String json = new Gson().toJson(vacationFormBeanList);

            // Write JSON string.
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");       

        return json;
    }

    @RequestMapping(value = "/vacation/saveResourceVacation", method = RequestMethod.POST)
    public
    @ResponseBody
    void saveResourceVacation(@RequestBody String jsonString, Principal principal) throws Exception {
        List<String> resourceVacations = extractVacationDatesFromJsonObject(jsonString);

    }

VacationFormBean:

假期表格豆:

public class VacationFormBean {
    int id; // (With Setter & Getter)
    String title; // (With Setter & Getter)
    String start;  // (With Setter & Getter)
    String url; // (With Setter & Getter)
}

I need something like that :

我需要这样的东西:

enter image description here

在此处输入图片说明

======================UPDATE=========================

======================更新==========================

I have add the click event as a result of domi27 recomendation. Kindly review the freemarker updates. I have added a java script method that uses :http://arshaw.com/fullcalendar/docs/event_data/removeEvents/

作为 domi27 推荐的结果,我添加了点击事件。请查看 freemarker 更新。我添加了一个使用的 java 脚本方法:http: //arshaw.com/fullcalendar/docs/event_data/removeEvents/

The new JS method :

新的 JS 方法:

   $('#calendar').fullCalendar('removeEvents', 1);

This method works perfectly with the events that was initially loaded from the controller. However,whenever I try to use the same method to remove the new events I have just added,Nothing happens. When I fire the "select event" for the new event I created ,I get for its id"undefined".

此方法与最初从控制器加载的事件完美配合。但是,每当我尝试使用相同的方法删除刚刚添加的新事件时,什么也没有发生。当我为我创建的新事件触发“选择事件”时,我得到它的 id“undefined”。

As I've mentiond on my freemarker,that are the lines I use to build the new event object that I aappend to the list.

正如我在我的 freemarker 上提到的,这些是我用来构建附加到列表的新事件对象的行。

var newVacation = {id:'133',title:'title',start:start,url: 'title'};
                                    resourceVacation.push(newVacation);

When I debug my script,I observe a difference among the objects loaded from the controller and the new object I created when the user adds a new event.

当我调试我的脚本时,我观察到从控制器加载的对象和我在用户添加新事件时创建的新对象之间的差异。

Here is the old object I got from the controller when I initiated the calendar: enter image description here

这是我启动日历时从控制器获得的旧对象: 在此处输入图片说明

Here is the new Object I got after I insert the new event:

这是我插入新事件后得到的新对象:

enter image description here

在此处输入图片说明

回答by domi27

You may implement it like this :

你可以这样实现:

  1. Fetch click on an event
  2. Display information about (how to) delete this event
  3. Call an ajax request to process deletion of event in backend
  4. Delete event from calendar frontend
  1. 获取点击事件
  2. 显示有关(如何)删除此事件的信息
  3. 调用ajax请求处理后端删除事件
  4. 从日历前端删除事件

1) First is described here : http://arshaw.com/fullcalendar/docs/mouse/eventClick/

1)首先在这里描述:http: //arshaw.com/fullcalendar/docs/mouse/eventClick/

2) Quite simpliest JS: confirm("Really want to delete this event ?")

2) 非常简单的 JS:confirm("真的要删除这个事件吗?")

3) Call a delete action via jQuery likely as you do to save a reservation

3) 像保存预订一样通过 jQuery 调用删除操作

4) Remove this event via fullcalendars "removeEvents" method : http://arshaw.com/fullcalendar/docs/event_data/removeEvents/

4)通过fullcalendars“removeEvents”方法删除此事件:http://arshaw.com/fullcalendar/docs/event_data/removeEvents/

Here's a short and very basic example :

这是一个简短且非常基本的示例:

eventClick: function(calEvent, jsEvent, view) {
    /**
     * calEvent is the event object, so you can access it's properties
     */
    if(confirm("Really delete event " + calEvent.title + " ?")) {
        // delete event in backend
        jQuery.post(
            "/vacation/deleteEvent"
            , { "id": calEvent.id }
        );
        // delete in frontend
        calendar.fullCalendar('removeEvents', calEvent.id);
    }
}

回答by Echo

I have make it work by the following approach: whenever the user fires whether the "select" or "click" event over the full calendar, I go to and search by the date the user selected and remove it from the my JS array. I use :$('#calendar').fullCalendar('removeEvents', id) to remove it from the full calendar event.

我通过以下方法使其工作:每当用户在整个日历上触发“选择”或“点击”事件时,我都会按照用户选择的日期进行搜索并将其从我的 JS 数组中删除。我使用 :$('#calendar').fullCalendar('removeEvents', id) 将其从完整日历事件中删除。

[#ftl /]
<script type="text/javascript">
var resourceVacation;
var vacationStart;

function censor(censor) {
    return (function() {
        var i = 0;
        return function(key, value) {
            if (i !== 0 && typeof(censor) === 'object' && typeof(value) == 'object' && censor == value)
                return '[Circular]';

            ++i; // so we know we aren't using the original object anymore

            return value;
        }
    })(censor);
}



function isVacation(day) {
    for (var index = 0; index < resourceVacation.length; index++) {
        if (resourceVacation[index].id == day) {
            return true;
        }
    }
    return false;
}

function deleteVacation(day) {
    for (var index = 0; index < resourceVacation.length; index++) {
        if (resourceVacation[index].id == day)

            resourceVacation.splice(index,1);
    }  

}

function showTheCorrectDialog(vacationStartDay) {
    var vacationID = $.fullCalendar.formatDate(vacationStartDay, "yyyy-MM-dd")
    if (isVacation(vacationID))
        getDeletionConfirmationDialog(vacationID);
    else
        getInsertionConfirmationDialog(vacationStartDay)
}


function doAjax() {

    $.each(resourceVacation, function(index) {
        var tmpDate = resourceVacation[index].start;

        tmpDate.setHours(tmpDate.getHours() - tmpDate.getTimezoneOffset() / 60);
        resourceVacation[index].start = tmpDate;

    });
    var test = JSON.stringify(resourceVacation, censor(resourceVacation));
    var x = test;
    $.ajax(
    {
        url:"[@spring.url '/vacation/saveResourceVacation'/]",
        type: "POST",
        data :x ,
        dataType: "json",
        contentType: "application/json"
    });
}


$(document).ready(function() {
    var date = new Date();
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();
    $.getJSON('[@spring.url '/vacation/loadResourceVacation'/]', function (data) {
        var calendar = $('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            selectable: true,
            selectHelper: true,
            select:
                    function(start, end, allDay) {
                        vacationStart = start;
                        showTheCorrectDialog(vacationStart);

                    },

            eventClick: function(calEvent, jsEvent, view) {

                showTheCorrectDialog(calEvent.start);

                // change the border color just for fun
                $(this).css('border-color', 'red');
            },

            editable: true,
            events
                    :
                    data
        });
        resourceVacation = data;
    });
});


function getInsertionConfirmationDialog(vacationStart) {
      var complimentaryVacationHTML = "<input  type = \"radio\" name = \"vacationTypes\" value = \"Complimentary\">Complimentary<br>";

    var scheduledVacationHTML = "<input  type = \"radio\" name = \"vacationTypes\" value = \"Scheduled\" checked=\"checked\">Scheduled<br>";


    $('html').append('<div id="insertionConfirmDialog" align="left">' +
            complimentaryVacationHTML +scheduledVacationHTML + ' </div > ');
    var selectedVacationType = "";
    var insertionConfirmDialog = $('#insertionConfirmDialog');
    insertionConfirmDialog.dialog({
        modal: true,
        autoOpen: false,
        resizable:false,
        title: 'Please select the vacation type',
        width: 300,
        height: 310,
        buttons: {
            'Ok': function() {
                selectedVacationType = $(this).find('input:checked').val();
                $(this).remove();

                vacationStart.setHours(vacationStart.getHours() - vacationStart.getTimezoneOffset() / 60);
                var vacationID = $.fullCalendar.formatDate(vacationStart, "yyyy-MM-dd")

                var newVacation = {id:vacationID,title:selectedVacationType,start:vacationStart};
                resourceVacation.push(newVacation);
                $('#calendar').fullCalendar('refetchEvents',
                {
                    title: selectedVacationType,
                    start: vacationStart,

                    allDay: true
                },
                        true // make the event "stick"
                        );

                $('#calendar').fullCalendar('unselect');
            },
            Cancel: function() {
                $(this).remove();
            }
        }
    });

    insertionConfirmDialog.dialog('open');
}

function getDeletionConfirmationDialog(vacationStart) {


    $('html').append('<div id="deletionConfirmDialog" align="left"><p>Are you sure you need to delete your vacation on:'+vacationStart +'</p>'+
            ' </div > ');
    var deletionConfirmDialog = $('#deletionConfirmDialog');
    deletionConfirmDialog.dialog({
        modal: true,
        autoOpen: false,
        resizable:false,
        title: 'Delete Confirmation',
        width: 300,
        height: 310,
        buttons: {
            'Delete': function() {
                $(this).remove();

                deleteVacation(vacationStart);
                $('#calendar').fullCalendar('removeEvents', vacationStart);

            },
            Cancel: function() {
                $(this).remove();
            }
        }
    });

    deletionConfirmDialog.dialog('open');
}


</script>
<style type='text/css'>


    body {
        margin-top: 40px;
        text-align: center;
        font-size: 14px;
        font-family: "Lucida Grande", Helvetica, Arial, Verdana, sans-serif;
    }

    #calendar {
        width: 900px;
        margin: 0 auto;
    }

</style>
<body>
<input type="button" id="editProject" name="editProject" class="btn btn-inverse"
       value="Save Vacations"
       onclick="doAjax()"
        />


<div id='calendar'></div>

</body>
[@footer/]