【发布时间】:2019-12-24 10:24:24
【问题描述】:
我正在 aurelia 上开发一个自定义属性,让用户在输入文本区域时从列表中进行选择。例如,用法将是这样的:
<textarea value.bind="description" placeholder="your description here" auto-complete></textarea>
您可能已经注意到,auto-complete 是属性。现在,当我想显示提示时,我想在自定义元素中执行此操作以保持简单。所以属性的附加方法会是这样的:
attached() {
this.containerElement = document.createElement('div');
this.containerElement.style.position = 'relative';
const ce = document.createElement('autocomplete-menu');
this.containerElement.appendChild(ce);
const ceView = this.templatingEngine.enhance(ce);
ceView.attached();
const currentParrent = this.element.parentElement;
currentParrent.replaceChild(this.containerElement, this.element);
this.containerElement.appendChild(this.element);
}
现在它打开并成功显示提示区域。截图:
当我想从属性视图模型与生成的元素进行通信时,问题就开始了。例如,我想将数据发送到它的视图模型或将某个对象绑定到它的可绑定属性。对于这个问题,我找到了以下解决方案:
https://discourse.aurelia.io/t/dynamically-add-custom-attribute-to-element/1400/6 https://ilikekillnerds.com/2016/01/enhancing-at-will-using-aurelias-templating-engine-enhance-api/
并阅读本文的最后一部分:
https://aurelia.io/docs/binding/how-it-works#abstract-syntax-tree
并发现,我必须为元素的视图模型引入一个对象作为它的 bindingContext 或 overrideContext。所以如果我是对的,我已经测试了以下解决方案:
this.containerElement.appendChild(ce);
let vm = { test: 1 }
const ceView = this.templatingEngine.enhance({ element: ce, bindingContext: vm });
ceView.addBinding(vm);
ceView.attached();
和
this.containerElement.appendChild(ce);
let vm = { test: 1 }
const ceView = this.templatingEngine.enhance(ce);
ceView.bind(vm);
ceView.attached();
console.log(ceView);
但在附加的元素生命周期钩子上,我记录了视图模型并注意到 this 上不存在 bindingContext 属性。
现在有两个问题:
- 上述解决方案有什么问题,如何将此类数据发送到增强元素?
- 有没有办法用
bindables 的已知方法来做到这一点?我的意思是在元素视图模型上定义一个可绑定属性,并在增强方法完成后绑定到它。而不是使用 bindingContext 和 overrideContext?
【问题讨论】:
标签: data-binding aurelia template-engine