我有一个自定义组件,我想向它传递一个对象,我该怎么做?传递字符串很容易,但我无法发送任何可观察或不可观察的内容。
main-page.js
exports.onInit = function(args) {
var page = args.object;
var pageData = new Observable();
page.bindingContext = pageData;
pageData.set('customObject', {label: 'This is my Label'});
// I've tried Observable as well, same undefined
// pageData.set('customObject', new Observable({label: 'This is my Label'}));
}
main-page.xml
<Page xmlns:customOtherControls="xml-declaration/mymodulewithxml">
<customOtherControls:MyControl myString="Works fine" myObject="{{customObject}}" />
<StackLayout>
<Label text="{{customObject.label}}" />
</StackLayout>
</Page>
mymodulewithxml.xml
<StackLayout loaded="onMymodulewithxmlInit">
<Label text="{{myString}}" />
<Label text="{{myObject.label}}" />
</StackLayout>
mymodulewithxml.js
function onMymodulewithxmlInit(args) {
console.log('myString', page.myObject); // "Works fine"
console.log('myObject', page.myObject); // undefined
}
最佳答案
如果您希望能够传入对象并连接事件(即 <custom:theWidget data="{{ myDataObj }}" onSave="theSaveCallback" />
),您需要创建一个插件。使用插件,您可以扩展现有项目(例如 StackLayout),然后创建通过对象连接的属性绑定(bind)。
在查看现有插件示例时,请密切注意 new dependencyObservable.Property(...)
的用法因为这些依赖关系可观察量实际上是自定义组件的属性(属性)的连接。这是一个示例:https://github.com/bradleygore/nativescript-materialdropdownlist/blob/master/materialDropdownList.ts#L92
关于javascript - native 脚本 : How to pass object from Page to Custom component with data-binding?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37313514/