本机脚本中自定义组件和页面之间的事件

问题描述 投票:0回答:1

在我的NativeScript(JS / Core)应用程序中,我有一个带有按钮的自定义组件:

mycomp.xml

<!-- mycomp.xml -->
<StackLayout loaded="onLoaded">
  <Button text="{{ label }}" tap="onTap" />
  ...
</StackLayout>

mycomp.js

/* mycomp.js */
function onLoaded(args) {
    const obj = args.object;
    obj.bindingContext = {
        label: obj.label
    };
}

function onTap(args) {
    console.log('comp button tap'); // fired
}

page.xml

<!-- page.xml -->
<Page xmlns:mycomp="components/mycomp" xmlns="http://schemas.nativescript.org/tns.xsd">
...
<mycomp:mycomp label="Test" tap="onButtonTap" />
...
</Page>

page.js

/* page.js */
exports.onButtonTap = function(args) {
  console.log('Button Tap'); // not fired
}

如何将组件内的轻击事件传递给页面事件“ onButtonTap”?

javascript events data-binding components nativescript
1个回答
0
投票
因为我想在不同的页面上多次使用组件,所以我在这里的注释的帮助下制定了该解决方案。

// home-view-model.js const fromObject = require("tns-core-modules/data/observable").fromObject; function createViewModel() { var viewModel = fromObject({ compdata: { foo: "bar", ontap: function(args) { console.log('button tap'); } } }); return viewModel; } exports.createViewModel = createViewModel;

<!-- home-page.xml -->
<Page xmlns:mycomp="components/mycomp" xmlns="http://schemas.nativescript.org/tns.xsd">
...
<mycomp:mycomp compdata="compdata" />
...
</Page>
// mycomp.js
const fromObject = require("tns-core-modules/data/observable").fromObject;
function onLoaded(args) {
    const obj = args.object;
    obj.bindingContext = fromObject(obj.compdata);
}
<!-- mycomp.xml -->
<StackLayout loaded="onLoaded">
  <Button text="{{ foo }}" tap="{{ ontap }}" />
  ...
</StackLayout>
© www.soinside.com 2019 - 2024. All rights reserved.