Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sub-observables with Knockout ES5

Ryan N uses a technique he calls "sub-observables" in a couple posts, where he hangs observables off of "parent" observables. It looks like this:

var parent = ko.observable("I'm the parent");
parent.sub = ko.observable("I'm the child");

parent()        //="I'm the parent"
parent.sub()    //="I'm the child"

It's a very handy technique, and I've used it in several extenders. With the Knockout ES5 plugin, this looks like its going to be impossible to access unless you call get getObservable() on the viewmodel. In bindings this is going to look ugly, but sometimes you just don't have access to the object that the parent is attached to.

Is there an ES5 compatible method for creating and accessing sub-observables?

like image 807
Kyeotic Avatar asked Jan 30 '14 21:01

Kyeotic


1 Answers

You could try to create a new class for your observable hierarchy:

function complexObservable(value, parent) {
    self = this;
    self.value = ko.observable(value); 
    self.parent = parent;
}

Then in your main view model you could have:

var parent = ko.observable("I'm the parent");
parent.sub = ko.observable(new complexObservable("I'm the child", parent));
like image 179
mrtig Avatar answered Oct 20 '22 19:10

mrtig