Sub-observables with Knockout ES5
Asked Answered
B

1

6

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?

Begga answered 30/1, 2014 at 21:44 Comment(2)
This was discussed on Github: github.com/SteveSanderson/knockout-es5/issues/2Combo
Looks like this is an unsolved problem, there hasn't been any activity on that discussion in several months (like Knockout-ES5 itself). I'm a little apprehensive about adopting this now.Begga
O
1

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));
Octodecillion answered 3/3, 2014 at 0:42 Comment(1)
I think maybe you are missing the point of the knockout es5 pluginBegga

© 2022 - 2024 — McMap. All rights reserved.