This project has moved and is read-only. For the latest updates, please go here.
1

Closed

callback function is not working as expected in button array of objects

description

callback function for links/buttons is not working as expected with notify.js

If there are multiple child records and if we want to show the comma separated links it is showing wrong result on callback.
we are using for loop to create array of objects to add multiple links in single notification, when we click on notification link, it is showing last added link name.

please check below code where I have added alert , it always showing last added id and name in alert.

var len = results.length;
for (var i = 0; i < len; i++) {
var temp_item = results[i];
arr.push({
"type": "link",
"text": temp_item.ap_name,
"callback": function () {
alert("automation id: " + temp_item.ap_automationId + " Automation name: " + temp_item.ap_name); } }); }
Closed Dec 9, 2016 at 9:44 PM by Liger_cp <SND\Liger_cp>
Not an issue with the library, just an issue with JavaScript in general..

comments

Liger wrote Dec 9, 2016 at 9:42 PM

Hi, this is due to the way that JavaScript accesses the variables at the time of calling the event. Basically it just uses the last assigned value, which will be the last result in the array.

To get around this you can wrap the function in another function which executes at runtime, and assigns the correct value to the callback.
var len = results.length;
for (var i = 0; i < len; i++) {
    var temp_item = results[i];
    arr.push({
        "type": "link",
        "text": temp_item.ap_name,
        "callback": (function (temp_item) { 
            return function() { 
                alert("automation id: " + temp_item.ap_automationId + " Automation name: " + temp_item.ap_name); 
            }
        })(temp_item)
    });
}
Hope that helps
Paul

wrote Dec 9, 2016 at 9:44 PM