How to set up visibility binding in JavaScript


#1

Hi,

I try to define some databinding in JavaScript Code, like I usually did in XML before:

<ActivityIndicator busy="{{ isLoading }}" visibility={{ isLoading ? 'visible' : 'collapse' }} />

Now it is necessary for me to define this in JavaScript, as I need to create the UI dynamically in JavaScript.

I tried to define the busy binding and visibility binding like this:

activityIndicator.bind({               //works
   sourceProperty: "isLoading",
   targetProperty: "busy",
   twoWay: true
}, myObservable);
 
activityIndicator.bind({               //does NOT work
   sourceProperty: "isLoading" ? 'visible' : 'collapse',
   targetProperty: "visibility",
   twoWay: true
}, myObservable);

The busy binding works as expected, but not the visibility-binding. When the ActivityIndicator is not busy, it should not consume any space, but it does as you can see here:

I tried this with NativeScript 2.3 and 2.4. So it seems that I am generally making a mistake.

Can you tell me what I am doing wrong?

Thank you in advance!


#2

Instead of “collapse” it should be “collapsed”.


#3

Hi, thanks for your response. But according to the docs, ‘collapse’ is the correct one.
http://docs.nativescript.org/api-reference/modules/ui_enums.visibility.html#collapsed


#4

Hah thanks I didn’t noticed that it was obsoleted sorry about that.


#5

I think you may need to use the expression property as well. You still want to bind it to the isLoading property but provide the expression that gets evaluated. I don’t typically bind this way so I haven’t tried this yet.

Reference: https://github.com/NativeScript/nativescript/blob/9f7ce6f/tns-core-modules/ui/core/bindable.d.ts#L23

Edit: In your case it would be the following:

 activityIndicator.bind({               
    sourceProperty: "isLoading"
    targetProperty: "visibility",
    twoWay: true,
    expression: "isLoading ? 'visible' : 'collapse'"
 }, myObservable);

#6

Ahhh… I somehow missed that expression property. Not everything works.
Thank you very much! :beers: