简体   繁体   中英

KnockoutJS if binding with multiple elements

I thought this would be a simple thing, but I basically have an observable array of objects which contain data like:

{
   BasicType: "some-type",
   ExtendedType: "some-extended-type",
   DisplayType: "some-display-type"
}

The data fields are always in the model, just they will be empty strings if there is no data for them to display.

Now this model is used throughout the system and is a simple POJO and the view model just contains many of these as and when they are needed in the views. So I dont want to put any view specific concerns on "this" object however can put them in the view model which is composed of lots of these smaller models.

Anyway in the view all fields are added but each has an if to disable it if there is a more applicable type available. So an example would be something like:

<div data-bind="text: BasicType, if: (BasicType && !ExtendedType && !DisplayType)"/>
<div data-bind="text: ExtendedType, if: (!BasicType && ExtendedType && !DisplayType)"/>
<div data-bind="text: DisplayType, if: (!BasicType && !ExtendedType && DisplayType)"/>

However for some reason it doesn't do as I would expect, I have tried changing the !xType for xType == '' however no such luck there either, and also used the parentheses to force evaluation but nothing. So am I missing something or can the knockoutjs if not handle multiple elements?

I would be happy to just convert these into computed observables if there was a simple way to do it, but as these models are used across pages and as a contract with a webservice (they are like the data layer) I don't want to change them, and I do not know how I could otherwise add the computed values to the objects unless when I get them I loop round each one adding the computed observables to each then using that.

Anyway that's the scenario, any advice would be great!

Your code will work if the model properties are not observables. If the model properties are observables, you need to execute the observables to get access to the values before comparing.

<div data-bind="foreach: types">
    <div data-bind="text: BasicType, if: (BasicType() && !ExtendedType() && !DisplayType())"></div>
    <div data-bind="text: ExtendedType, if: (!BasicType() && ExtendedType() && !DisplayType())"></div>
    <div data-bind="text: DisplayType, if: (!BasicType() && !ExtendedType() && DisplayType())"></div>
</div>

Here's an example: http://jsfiddle.net/5WMVb/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM