Bind to object method in JavaScript


#1

I’m having trouble binding to an object method when creating the binding in JavaScript. Here’s what I would normally do in XML:

<Label text="{{ name }}" opacity="{{ isActive() ? 1 : .5 }}" />

Where isActive() is a calcuated property on my object. This generally works from the XML binding. So how do you do this in JavaScript? Current attempt that doesn’t work:

let lbl = new Label();
lbl.bindingContext = observableCustomer;
lbl.bind({ sourceProperty: "name", targetProperty: "text", twoWay: false});
lbl.bind({ sourceProperty: "isActive()", targetProperty: "opacity", twoWay: false, expression: "(isActive()) ? 1 : .5" });

If I were to make isActive() a static instance property, then it will work. I just can’t figure-out how to work with methods/calculated properties from JavaScript. Ideas?


#2

AND now I realize what I’m doing wrong…

I was not properly using the set and get keywords in my types.

WRONG

class Whatever {
   constructor(public name: string) { }

   public isActive(): boolean {
      return true;
   }
}

RIGHT

class Whatever {
   constructor(public name: string) { }

   public get isActive(): boolean {
      return true;
   }
}

When you add the get (and set if not readonly) keywords, the JavaScript bindings like this work fine:

lbl.bind({ sourceProperty: "isActive", targetProperty: "opacity", twoWay: false, expression: "isActive ? 1 : .5" });

SO…lesson learned…if you want to use calculated properties that work in bindings, don’t forget the get and set keywords. (I assume the reason it works okay without these keywords in XML bindings is because the property is treated like a binding expression function. ¯\(ツ)/¯)