在我的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”?
// 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>