Frage

I'm using the ko mapping plugin to create my observables from a JS object, ko.mapping.fromJS().

A snippet of the object is below:

{ Name: "blah", Parent: { Title: "blah", Url: "/blah" } }

If Parent.Title changes then everything on my page is updating as expected, but when Parent becomes null I have a problem. The simplified markup that uses the Parent properties looks like this:

<p data-bind="if: HasParent">Up: <a data-bind="text: ParentTitle"></a></p>

HasParent looks like this:

self.HasParent = ko.computed(function () {
    return self.Parent;
});

ParentTitle looks like this:

self.ParentTitle = ko.computed(function () {
    return self.HasParent() ? self.Parent.Title() : "";
});

Note: self is set to the result back from ko.mapping.fromJS() and then applied to the page by calling ko.applyBindings();

So basically my problem is the HasParent function is always returning a true-ish value.

Also, this is my first ko project so if I can do anything in a better way please let me know :)

Any help would be appreciated.

Thanks.

War es hilfreich?

Lösung

observables are functions, so even if their actual value is null, it will still be truthy when looking at the observable itself.

The if binding will unwrap your computed observable, but yours will have two levels that would need to be unwrapped to get to the actual value (the computed and then the actual observable).

You would want to return self.Parent() to have it work in the way that you intend. If you truly want a true/false value (not required for if) then you can do !!self.Parent().

Update:

The issue is that the mapping plugin only creates observables on the outer-most properties, so Title and Url will be observables, but not Parent. If you want your computed observable to actually respond to the Parent moving between null and populated, then it would need to be observable.

Andere Tipps

Parent isn't an observable; it's an object. HasParent won't ever get re-evaluated because it's not dependent on any observable. Changing your binding from if: HasParent to if: Parent should help you out.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top