从Nativescript中的按钮点击引用插件函数

时间:2016-04-26 13:55:51

标签: plugins nativescript

我真的很困惑插件中的代码逻辑流程。我正在使用这个seed并尝试在演示应用程序中创建一个按钮,该按钮从插件中调用一个函数,该插件只包含一个console.log,我有:

//yourPlugin.common.ts:
import * as app from 'application';
import * as dialogs from 'ui/dialogs';

export class Common {
  public message: string;

  constructor() {
    this.message = Utils.SUCCESS_MSG();
  }
}

export class Utils {
  //Utils Stuff - not relevant for this issue
}

 export function Click() {
      console.log("Clicked");
  }


//demo/app/main-view-model.ts:

import {Observable} from 'data/observable';
import {YourPlugin} from 'nativescript-yourplugin';

export class HelloWorldModel extends Observable {
  public message: string;
  private yourPlugin: YourPlugin;
  private Click: YourPlugin.Click;

  constructor() {
    super();

    this.yourPlugin = new YourPlugin();
    this.message = this.yourPlugin.message;
  }
}

然后在我的xml中,我将<Button text="This is Button!" tap="Click" />添加到了我的应用页面。但是,当我按下按钮时,控制台日志没有触发,我有什么问题?

更新

的xml:

<Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="pageLoaded">
  <StackLayout>
    <Label text="{{ message }}" class="message" textWrap="true"/>
    <Button text="This is Button!" tap="{{ Click }}" />
  </StackLayout>
</Page>

主page.ts:

import * as observable from 'data/observable';
import * as pages from 'ui/page';
import {HelloWorldModel} from './main-view-model';

// Event handler for Page "loaded" event attached in main-page.xml
export function pageLoaded(args: observable.EventData) {
    // Get the event sender
    var page = <pages.Page>args.object;
    page.bindingContext = new HelloWorldModel();

}

1 个答案:

答案 0 :(得分:2)

此语法:

import {YourPlugin} from 'nativescript-yourplugin'

仅从YourPlugin模块导入名为nativescript-yourplugin的类。因此,您无法访问main-view-model.ts文件中的任何其他内容。要访问插件中定义的其他内容,必须导入整个模块。同样在HelloWorldModel中,Click应该是一个函数,您只能将其定义为某种类型。而Click函数的更多内容并非公开。因此,您的代码应该类似于:

import {Observable} from 'data/observable';
import nsPlugin = require('nativescript-yourplugin');

export class HelloWorldModel extends Observable {
  public message: string;
  private yourPlugin: nsPlugin.YourPlugin;

  public Click = nsPlugin.Click;

  constructor() {
    super();

    this.yourPlugin = new nsPlugin.YourPlugin();
    this.message = this.yourPlugin.message;
  }
}

最后假设您将XML绑定到HelloWorldModel的实例,您的按钮应该如下所示:

<Button text="This is Button!" tap="{{ Click }}" />