dashman
dashman

Reputation: 3028

Getting a page view element from a model class

I've got a model class and would like to get access to a ui element.

frameModule.topmost().getViewById("id") or

frameModule.topmost().page.getViewById("id")

don't work.

Upvotes: 0

Views: 1096

Answers (2)

RcoderNY
RcoderNY

Reputation: 1764

There are many ways to get a reference to the Page object. The documentation is a good reference to learn about them: https://v7.docs.nativescript.org/ui/components/page#page-reference

To answer you question, the usual way to get a reference to the Page object inside a view model class is by using the EventData passed to each event like a tap event when a Button is tapped.

onButtonTap(args: EventData) {
  const button = args.object as Button;
  const page = button.page;
  // ...
}

Upvotes: 0

Dean Le
Dean Le

Reputation: 2094

As I understand what you need, I hope this solution would help.

In XML, assuming that you have UI Element with an ID. You will get it in the controller. For example:

In page.xml:

<Label id="test"/>

In the binding object class in page-view-model.js, create a property that has type of label:

var labelModule = require("ui/label");
var Label = labelModule.Label;

class Someclass extends Observable {
    public label: Label;
}

In page.js:

function pageLoaded(args) {
    var page = args.object;
    var myLabel = page.getViewById("test");
    var context = new Someclass();
    page.bindingContext = context;
    context.label = myLabel;
}

Upvotes: 3

Related Questions