Nativescript custom properties


#1

I’m struggling to change custom property value in a UI control created using code-only file approach. I have my custom control which works well but I bump into problems when I try to change property values. Take a look at sampled code:

XML:
<CustomControl:MyControl data = ‘{{ list }}’ selectedValue = “{{ selectedText }}” />

view-model:
var Mydata = [‘USA’,‘NORTH KOREA’,‘RUSSIA’];
viewModel.set(‘list’, Mydata);

MyControl.js:
Object.defineProperty(QuestionControl.prototype, “data”, {
get: function () {
return this._data;
},
set: function (value) {
this._data = value;
this.populateData();
}
});

Object.defineProperty(QuestionControl.prototype, “selectedValue”, {
get: function () {
return this._selectedValue;
},
set: function (value) {
this._selectedValue = value;
this.notify({object: this, eventName: observable_1.Observable.propertyChangeEvent, propertyName: ‘SELECTEDVALUE’, value: value});
console.log(value)
},
enumerable: true,
configurable: true
});

I’m able to receive data from the view-model. The challenge I’m facing is to use MyControl.js to change selectedValue property and let the view-model know of the changes. Can someone point me in the right direction


#2

Hi @mbayi
Is it possible for you to set this up on NativeScript playground?
play.nativescript.org


#3

Yes, I’ll set it up. Thanks for reaching out


#4

You seem using the traditional JavaScript properties, but you are suppose to handle this situation with built-in Observable which handles propertyChange event by default / Property api which is usually used when implementing updates on native view.

If you custom component is nothing more than wrapped NativeScript components, you can simply play with bindingContext. Here is an example

Read more about custom components here.


#5

I have tried all the possible solutions I could think of using the Observable but it doesn’t work. I’ve sett it up on nativecsript playground.


#6

Please check https://play.nativescript.org/?templ66ate=play-js&id=uo0pck


#7

I see that you are trying to implement auto complete text view, but did you give a try for ProUI AutoCompleteTextView


#8

Like @manojdcoder said, I’d recommend to use AutoCompleteTextView from Pro UI instead


#9

I have seen controls like nativescript-dropdown implement this functionality, what I can’t seem to wrap my head around is how it updates the selectedIndex property form the code-behind.


#10

As you see here, it uses the Properties System only as already mentioned in my comment above.


#11

Thank you @manojdcoder for the insights,
I wasn’t able to use the observable module to update the control’s properties but the control is working as expected.
So far, so good.
I have put the source code on GitHub for anyone interested in a simple
AutoComplete control in android. In the future, maybe I’ll extend it and make
a community plugin around it.