Search code examples
javascriptjqueryjquery-eventsbootstrap-notify

Bootstrap-Notify - Hook into events


Introduction

I'm using the Bootstrap-Notify script to display great visual alerts to my users. But to use the full strength of the script I want to hook into the events of the script. Unfortunately, there is no example either in the documentation or on other open-source platforms like GitHub.


My approach

As described in the Documentation I've linked above, I used the onClose attribute together with a function:

$(document).ready(function() {
  //Notifications
  var welcome = $.notify({
    message: "Test"
  }, {
    onClose: test()
  });
});

function test() {
  console.log("onClose");
}

I've made a short fiddle to show you that it doesn't work as thought (in my case the test function which should be called on close of the notification triggers already on script start). Other approaches like welcome.onClose(test()); also failed.


So, how to hook into the events of Bootstrap-Notify succesfully?


Solution

  • The problem is that you are not passing a reference to test as the notify onClose function, you are passing the result of the function!

    you want to do this:

    $(document).ready(function() {
      //Notifications
      var welcome = $.notify({
        message: "Test"
      }, {
        onClose: test
      });
    });
    

    or if you only wanted to modify the test function (and not the $.notify part), you would need to do this:

    function test() {
      return function() {
         console.log("onClose");
      };
    }
    

    the argument to onClose should be a function