How to change the text of the xml based textField via main-page.js? Im using this.set("message", getMessage(this.counter));
to change the values via main-view-model.js. But that scenario is not working when I try in it in main-page.js. How to do this? :-) And I need an explanation to my main question. Thanks in advance.
I assume you talking about the "Hello World" NativeScript application that can be found here. The difference is that the main-page.js is the "code behind" of the main-page.xml (note that naming convention is important for {N} to make the match) and the main-view-model.js is a separate file which has been assigned as bindingContext
to the Page of the main-page.xml in its navigatingTo event as you can see here:
function onNavigatingTo(args) {
/*
This gets a reference this page’s <Page> UI component. You can
view the API reference of the Page to see what’s available at
https://docs.nativescript.org/api-reference/classes/_ui_page_.page.html
*/
var page = args.object;
/*
A page’s bindingContext is an object that should be used to perform
data binding between XML markup and JavaScript code. Properties
on the bindingContext can be accessed using the {{ }} syntax in XML.
In this example, the {{ message }} and {{ onTap }} bindings are resolved
against the object returned by createViewModel().
You can learn more about data binding in NativeScript at
https://docs.nativescript.org/core-concepts/data-binding.
*/
page.bindingContext = createViewModel();
}
In order to change the text of the Label (TextView) of the main-page.xml in its code behind file you could ether get the Label via an id (getViewById()
example) or directly use the bindingContext
(your 'ViewModel'):
var createViewModel = require("./main-view-model").createViewModel;
var viewModel;
function onNavigatingTo(args) {
var page = args.object;
viewModel = = createViewModel();
page.bindingContext = viewModel;
}
// Example with event handler for a 'tap' event of a Button
function onButtonTap(args) {
viewModel.set("message", "New message set via code behind");
}