Why does the jQuery dialog keep crashing at $ (this)?

I have time trying to understand why the code below crashes when the dialog is closed or canceled. These are errors in the lines that use ($ this) in the dialog button function.

For some reason, if I hard code the values ​​in addTaskDialog.html (AddTaskForm); it works. I even hardcoded the returned ajax form, and it worked ... This problem occurs in all browsers.

  $(function ()
{

    /*
    *  Initializes AddTask Dialog (only needs to be done once!)
    */
    var $dialog = $('<div></div>').dialog(
{
    width: 580,
    height: 410,
    resizable: false,
    modal: true,
    autoOpen: false,
    title: 'Basic Dialog',
    buttons:
        {
            Cancel: function ()
            {
                $dialog.dialog('close');
            },
            'Create Task': function ()
            {

            }
        },
    close: function ()
    {
        $dialog.dialog('close');
    }
});


    /*
    * Click handler for dialog
    */
    $('#AddTask').click(function ()
    {

        /* Ajax request to load form into it */
        $.ajax({
            type: 'Get',
            url: '/Planner/Planner/LoadAddTaskForm',
            dataType: 'html',
            success: function (AddTaskForm)
            {
                $dialog.html(AddTaskForm);
                $dialog.dialog('open');
            }
        });
    });



});

});

+3
source share
2 answers

I get it. I'm not sure where I got this code, but it was causing problems, so I took it and everything works fine.

    close: function ()
{
    $dialog.dialog('close');
}
0
source

, , , . $(this) AddTaskDialogOptions, , $(this) $("#AddTask"), , $(this) , .

var that;
$('#AddTask').click(function ()
{
    that = $(this);
    /* Ajax request to load form into it */
    $.ajax({
        type: 'Get',
        url: '/Planner/Planner/LoadAddTaskForm',
        dataType: 'html',
        success: function (AddTaskForm)
        {
            var addTaskDialog = $('<div></div>');
            addTaskDialog.dialog(AddTaskDialogOptions);
            addTaskDialog.html(AddTaskForm);
            addTaskDialog.dialog('open');
        }
    });
});
var AddTaskDialogOptions = {
    width: 580,
    height: 410,
    resizable: false,
    modal: true,
    autoOpen: false,
    title: 'Basic Dialog',
    buttons:
        {
            Cancel: function ()
            {
                that.dialog('close');
            },
            'Create Task': function ()
            {

            }
        },
    close: function ()
    {
        that.dialog('destroy').remove();
    }
}
+1

Source: https://habr.com/ru/post/1790591/