Menu

Isolating scope with self executing anonymous function in PHP

Upgrading Ubuntu 18.04 to 18.10 was a snap!

Dev Blog

Knockout JS offers manual subscribing to observables, so that arbitrary code can be executed whether the observable value changes. This might be useful to update user interface when value changes, or to perform AJAX requests based on value of observable. For instance filters can be implemented, which will pull new data according to observable value. 

When using bare KnockoutJS the observable itself is object having method subscribe. Example of subscribing in bare KO:

app.model.filter.active.subscribe(function(newValue) {
    console.log("Perform AJAX request with: " + newValue);
});






However, when using EcmaScript 5 plugin, which allows using observables without parenthesis, the subscribe method is not available. The value of active field would appear as a plain JavaScript type, for instance boolean value. Luckily the KO have the method to obtain real observable with ko.getObservable where first parameter is view model, the latter one is observable name. The resulting code is a bit different that that from the bare KnockoutJS in terms of getting access to subscribe method:

ko.getObservable(app.model.filter, 'active').subscribe(function(newValue) {
    console.log("Perform AJAX request with: " + newValue);
});

When added explicit subscription with method above, just setting model value would execute function passed to subscribe method:

app.model.filter.active = true;
// console logs: Perform AJAX request with: true

See Also