如何从NativeScript自定义组件中公开方法?

时间:2016-07-11 07:11:39

标签: nativescript

我想在NativeScript项目中公开自定义组件的方法。这是概念设置:

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

MyComponent.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 }

问题:如何在自定义组件上正确公开myCustomMethod,以便托管页面可以通过JavaScript访问和调用它?

默认情况下,当尝试获取页面上自定义组件的引用时,将返回对自定义组件的布局容器的引用(在此示例中为StackLayout)。

所以,作为一种解决方法,我这样做:

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

这有点像黑客,但它正在发挥作用。有没有更好的方法来公开自定义组件方法,而不是为布局容器创建超类?

更新

为了更准确,自定义组件具有实例属性,因此最终解决方案需要支持像......这样的场景。

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

1 个答案:

答案 0 :(得分:0)

由于您要重用的方法未与您的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模式并通过绑定上下文公开您的方法。

相关问题