Вопрос

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

В настоящее время у меня есть следующее -

(function() {

    var global = this;
    global.confirmationBox = function() {
    config = {
        container: '<div>',
        message:''
    }
    return {
        config: config,
        render: function(caller) {
            var jqContainer = $(config.container);
            jqContainer.append(config.message);
            jqContainer.dialog({
                buttons: {
                    'Confirm': caller.confirm_action,
                     Cancel: caller.cancel_action
                }
            });
        }
    }
} //end confirmationBox
global.testWidget = function() {
    return {
        create_message: function(msg) {
            var msg = confirmationBox();
            msg.message = msg;
            msg.render(this);
        },
        confirm_action: function() {
            //Do approved actions here and close the confirmation box
            //Currently not sure how to get the confirmation box at
            //this point
        },
        cancel_action: function() {
            //Close the confirmation box and register that action was 
            //cancelled with the widget. Like above, not sure how to get
            //the confirmation box  back to close it
        }
    }
}//end testWidget
})();
//Create the widget and pop up a test message
var widget = testWidget();
widget.create_message('You need to confirm this action to continue');

В настоящее время я просто хочу сделать что-то такое же простое, как закрыть окно внутри виджета, но я думаю, что я обвел свой собственный мозг кругами в терминах того, что знает, что.Кто-нибудь хочет помочь прояснить мой одурманенный мозг?

Приветствия, Сэм

Результирующий код:

Я подумал, что людям, которые позже найдут эту тему в поисках решения аналогичной проблемы, может быть полезно ознакомиться с кодом, который является результатом полезных ответов, которые я получил здесь.

Как оказалось, в конце концов, это было довольно просто (как и большинство расстраивающих запутанных мыслей).

 /**
 * Confirmation boxes are used to confirm a request by a user such as
 * wanting to delete an item
 */
 global.confirmationBox = function() {
    self = this;
    config = {
        container: '<div>',
        message: '', 
    }
    return {
        set_config:config,
        render_message: function(caller) {
            var jqContainer = $(config.container);
            jqContainer.attr('id', 'confirmation-dialog');
            jqContainer.append(config.message);
            jqContainer.dialog({
               buttons: {
                   'Confirm': function() {
                       caller.confirm_action(this);
                    },
                   Cancel: function() {
                       caller.cancel_action(this);
                   }
               }
           });
        }
    }
 } // end confirmationBox

 global.testWidget = function() {
    return {
        create_message: function(msg) {
            var msg = confirmationBox();
            msg.message = msg;
            msg.render(this);
        },
        confirm_action: function(box) {
            alert('Success');
            $(box).dialog('close'); 
        },
        cancel_action: function(box) {
            alert('Cancelled');
            $(box).dialog('close'); 
        }
    }
}//end testWidget
Это было полезно?

Решение

Вы могли бы передать jqContainer функциям подтверждения / отмены.

В качестве альтернативы, назначьте jqContainer в качестве свойства вызывающего объекта.Поскольку функции подтверждения / отмены вызываются как методы вызывающего объекта, они будут иметь доступ к нему через this.Но это ограничивает вас отслеживанием одного диалогового окна для каждого виджета.

Другие советы

Попробуйте что-то вроде этого:

(function() {

    var global = this;
    /*****************This is new****************/
    var jqContainer;


    global.confirmationBox = function() {
    config = {
        container: '<div>',
        message:''
    }
    return {
        config: config,
        render: function(caller) { 

            // store the container in the outer objects scope instead!!!!
            jqContainer = $(config.container);

            jqContainer.append(config.message);
            jqContainer.dialog({
                buttons: {
                    'Confirm': caller.confirm_action,
                     Cancel: caller.cancel_action
                }
            });
        }
    }
} //end confirmationBox
global.testWidget = function() {
    return {
        create_message: function(msg) {
            var msg = confirmationBox();
            msg.message = msg;
            msg.render(this);
        },
        confirm_action: function() {
            //Do approved actions here and close the confirmation box
            //Currently not sure how to get the confirmation box at this point

            /*******Hopefully, you would have access to jqContainer here now *****/

        },
        cancel_action: function() {
            //Close the confirmation box and register that action was 
            //cancelled with the widget. Like above, not sure how to get
            //the confirmation box  back to close it
        }
    }
}//end testWidget
})();
//Create the widget and pop up a test message
var widget = testWidget();
widget.create_message('You need to confirm this action to continue');

Если это не сработает, попробуйте определить ваши обратные вызовы (confirm_action, cancel_action) как закрытые члены вашего объекта.Но они должны иметь доступ к внешней области вашего основного объекта.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top