why text changed is not reflected to viewmodel property

Viewed 70

I have a property name

var viewModel = observableModule.fromObject({
    name: "abcd",
    onUsernameChanged: function () {
      console.log("-->"+ viewModel.name)
    }
  });

textfield like below,

<TextField text="{{name}}" textChange="{{ onUsernameChanged }}"
                class="h2 description-label" />

When I change the text by typing, It always prints --->abcd only.

Why the viewmodel property is not updated ?

Playground Demo of problem

currently I'm reading the changed text like below, And this method is not flexible and easy to use like viewmodel

var view = require("ui/core/view");
var idUsername = view.getViewById(args.object, "idUsername");
2 Answers

By taking a look at your code, I am inferring that there is no binding between your view (the XML file containing the TextField—assuming you are using NativeScript Core) and your view-model (the javascript file where you have your observable viewModel).

When the textChange event emits, you are printing the stored value at your ViewModel over and over (name, in this case: abcd). For example, at first, your value is abcd, but the text might be empty. Later, you type A, and then it prints abcd again, and so on.

If you want to print the new text output TextField element, you have to use the output emitted by the event. Look at this excerpt:

const viewModel = observableModule.fromObject({
  name: "abcd",
  onUsernameChanged: function (eventData) {
    // eventData has information on the textChange event
    console.dir(eventData);
    // Do whatever you want with this data, such as updating the view model
  }
});

try using this.get()

console.log("-->"+ this.get('name'))
Related