How to use foreach binding (knockout.js) with the

2019-06-07 06:44发布

for some reason I cannot get a foreach binding to work with a $data object in it, I have posted the code on JSfiddle

the weird thing for me is that

<div data-bind="template: { name: 'input-template', foreach: $root.geometries['Kubus'].invoer }"></div> 

works, and that $data is 'Kubus'

but that

<div data-bind="template: { name: 'input-template', foreach: $root.geometries[$data].invoer }"></div> 

gives a javascript error message:

Unable to parse bindings. Message: TypeError: $root.geometries[$data] is undefined; Bindings value: template: { name: 'input-template', foreach: $root.geometries[$data].invoer }

  1. can you explain why this happens?
  2. can you tell me how I should do it so the error doesn't show?
  3. are there ways to do what I'm trying to do with more efficient code?

2条回答
啃猪蹄的小仙女
2楼-- · 2019-06-07 07:03

In case that you use $data it is an object, but not a string like 'Kubus'.

You should add new field like "name" to "geometries" and add method "getGeometryByName", where you will do something like this:

 self.getGeometryByName = function (geometryName) {
        var result= null;
        $.each(self.geometries(), function (index, value) {
            if (value.name() == geometryName) {
                result= value;
                return false;
            }
        });

        return result;
    }

Also is much easier to understand view code when you use model fields directly by name instead of with: + $data (from own development experience)

查看更多
在下西门庆
3楼-- · 2019-06-07 07:25

To me you are being too tricky with the with: dimSelect and with: geoSelect. Why not just use dimSelect() and geoSelect() directly?

http://jsfiddle.net/jearles/PYbzF/12/

查看更多
登录 后发表回答