How do you open methods from custom NativeScript components?

I want to expose a method from a custom component in a NativeScript project. Here is the conceptual installation:

MyComponent.xml <StackLayout loaded="loaded"> ...UI markup... </StackLayout>

Mycompponent.ts export function loaded(args) { //do stuff }; export function myCustomMethod() { //do more stuff };

MyPage.xml <Page xmlns:widget="..." loaded="loaded"> <widget:MyComponent id="myComponent" /> </Page>

MyPage.ts export function loaded(args) { let page = <Page>args.object; let widget = page.getViewById("myComponent"); widget.myCustomMethod(); //<--THIS DOES NOT WORK }

Question: How to place it myCustomMethodon a custom component so that the hosting page can access and call it through JavaScript?

By default, when you try to get a link to a custom component on the page, a link is returned to the layout container of the custom component (in this example).

So, as a workaround, I am doing this:

Mycompponent.ts export function loaded(args) { let stackLayout = <StackLayout>args.object; //Layout container stackLayout.myCustomMethod = myCustomMethod; //Attach custom method to StackLayout }

It's a little hack, but it works. Is there a better way to expose custom component methods without creating a superclass for the layout container?

UPDATE

, , , ...

MyComponent.ts let isStarted = false; export function loaded(args){ // do stuff }; export function myCustomMethod() { isStarted = true; };

+4
1

, , customCompoenent, , , . MyComponent.ts ( , , , MyCompoennt.ts, onLoaded, onNavigationgTo ..).

:

navigator.ts ( MyComponent.ts)

import frame = require("ui/frame");
export function navigateBack() {
    frame.goBack();
}

, :

MyPage.ts

import navigatorModule = require("navigator");

export function goBack(args: observable.EventData) {
    navigatorModule.goBack(); // we are reusing goBack() from navigator.ts
}

- MVVM .

0

All Articles