开发者

Deep observables and foreach templates

I have a view model like this:

function viewModel() {
   this.a = ko.observable();
}

At some point I try to do this (where m is my viewModel):

m.a(new thing());

Now, I have a template binding like this:

<ul data-bind="template: { name: 't', foreach: a().b }"></ul>

But it will crash before anything happens because a() is initially undefined or null. So I tried this variation:

<ul data-bind="template: { name: 't', foreach: a.b }"></ul>

But this is weird, because now it doesn't crash but renders a single empty item, using the template t and that's wrong.

I'm a bit at loss here, I thought the point was that I would be able to defined the source (like this) and as things changed it would just update stuff but I'm just getting errors (or nothing is happening) what I'm开发者_如何转开发 I doing wrong?


You can protect yourself from hitting an undefined property by writing your binding like this:

<ul data-bind="template: { name: 't', foreach: a() ? a().b : [] }"></ul>

Otherwise, you can push this concern to your view model and create a dependentObservable like:

viewModel.c = ko.dependentObservable(function() {
    return this.a() ? this.a().b : [];
}, viewModel);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜