0

I'm trying to extend alert function and let it close after a timeout.
I'm getting this error when close timeout expire:

cannot call methods on dialog prior to initialization; attempted to call method 'close'

The code of extension is:

$.extend({ alert: function (message, title) {
  $("<div></div>").dialog( {
    buttons: { "Ok": function () { $(this).dialog("close"); } },
    close: function (event, ui) { $(this).remove(); },
    resizable: false,
    title: title,
    modal: true,
    open: function(event, ui) {
        setTimeout(function(){
            $(this).dialog('close');   <-- Error is here
        }, 3000);
    }
  }).text(message);
}
});

And the call method is:

$.alert('Alert Message Test');

Next, after 3000 ms, the dialog should close. What's wrong?

UPDATE

Thanks to Kevin, now it works! Yes, it's the same problem of your reported answer but... it's so hard to find. This question is connected to the JS error.

$.extend({ alert: function (message, title) {
  $("<div></div>").dialog( {
    buttons: { "Ok": function () { $(this).dialog("close"); } },
    close: function (event, ui) { $(this).remove(); },
    resizable: false,
    title: title,
    modal: true,
    open: function(event, ui) {
        var that = this;            <-- This is the solution
        setTimeout(function(){
            $(that).dialog('close');
        }, 3000);
    }
  }).text(message);
}
});
Paolo A.
  • 43
  • 7
  • `this` isn't what you think it is. – Kevin B Apr 01 '16 at 21:24
  • try logging `this` inside your setTimeout function, it's probably not what you think it is. either reselect your dialog or use an arrow function for your setTimeout callback. – azium Apr 01 '16 at 21:24
  • @KevinB that duplicate should be updated to show using arrow syntax, as likely it's the way forward for these problems. Thoughts? – azium Apr 01 '16 at 21:28
  • eh, not quite yet. IE11 is still mainstream, doing so may cause more problems than it fixes due to people blindly using arrow functions not knowing browser support. – Kevin B Apr 01 '16 at 21:29
  • You 've opened my eyes!!!! – Paolo A. Apr 01 '16 at 21:30
  • @azium and, it's already in another answer in the dupe target. :p – Kevin B Apr 01 '16 at 21:31

0 Answers0