【发布时间】:2016-12-31 18:48:59
【问题描述】:
当绑定对象更新时,如何创建自定义元素的新实例? 假设我在视图中有一个可以由用户更改的 visitDate。当它改变时,我想更新页面的内容。 视图模型:
...
visitDateChanged() {
this.shifts = [];
this.newShift = {};
this.newShift = {pstart: this.visitDate, pstop: this.visitDate});
this.service.getData(this.visitDate)
.then(result => this.shifts = result);
}
}
查看:
<div repeat.for="shift of shifts | filterDate: visitDate">
<shift-form shift.bind="shift" shifts.bind="shifts"></shift-form>
</div>
<div>
<shift-form shift.bind="newShift" shifts.bind="shifts"></shift-form>
</div>
注意:shift-form 是一个自定义元素。现在,如果我在视图中更改 visitDate,它会调用 visitDateChanged() 并更新 newShift 和 shift 变量。它分离所有在 div repeat.for 中调用的 shift-form 实例,并根据 shifts 数组中的对象附加新实例。但它不会在第二个 div 中分离和重新附加 shift-form(不会创建 shift-form 的新实例)。当重新创建 newShift 时,我需要在 div 中创建一个新的 shift-form 实例。我设法通过将 newShift 从一个对象更改为一个数组来做到这一点。那么
<div repeat.for="shift of newShift">
<shift-form shift.bind="shift" shifts.bind="shifts"></shift-form>
</div>
可以解决问题,但我认为这不是一个优雅的解决方案
【问题讨论】:
-
如何创建一个
shiftChanged函数让您知道shift属性何时更改(重置newShift 时)?您介意解释一下为什么需要重新创建整个自定义元素吗? -
是的,我可以解释。 shift-form 有很多由自定义元素的方法设置的变量,如果我使用 shiftChanged,它们都需要重置。这实际上是更多的代码,我可能会不小心忘记重置一些变量。
-
我不确定您要做什么,但是您为什么不删除第二个“newshift”表单,然后将一个新项目(可能是一个空对象)推到班次数组?然后将为您创建/销毁 shift-form。
标签: javascript data-binding aurelia custom-element