Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute function after all observableArray dependencies executed in knockout.js

I have an observableArray. I want to execute a function after deletion or addition of an item from an observableArray and after completion of all its dependency subscription calls. Like :

 observableArray.push(newObject);

 //I can't put my function call at this point because if any subscription is..
 //with newObject or observableArray will execute asynch, and i.. 
 //want my function to execute after all such subscription execution.  

Is there any way to achieve this in knockout ?

like image 346
Gaurav Avatar asked Mar 08 '13 11:03

Gaurav


2 Answers

I'm not sure if observableArray.push() will return true, but give this a shot;

if (observableArray.push(newObject)) {
    console.log(observableArray);
}
like image 74
bmorenate Avatar answered Oct 07 '22 02:10

bmorenate


I thought that events were fired asynchronously, so I wrote the following Live JSFiddle :

var flagUpdater = ko.observable(0),
    aList = ko.observableArray(["Foo", "Bar", "Baz"]);

flagUpdater.subscribe(function() {
  console.log("Change the flag now!");
});

aList.subscribe(function() {
  console.log("Schedule flag update");
  flagUpdater("blah");
});

aList.push("Qoo");

but it doesn't work. It seems that callbacks are all processed synchronously, ie all callbacks already returned once the modifier function (push() for example) has returned. So you can simply set the flag after manipulating the array (live):

aList.push("Qoo");
flag = "CHANGED";
console.log("Flag is now " + flag);
like image 45
Raffaele Avatar answered Oct 07 '22 02:10

Raffaele