javascript - ObservableArray.push() 不通知视图
问题描述
我以这种标准方式在自动完成搜索栏下创建要建议的项目列表:
我想通过将它们一一推送到具有条件的 ObservableArray 来逐步填充建议项:
page.bindingContext.set("suggestionItems", new ObservableArray([]));
for (let i = 0; i < source.length; i++){
if ( conditionMet(source[i]) ){
page.bindingContext.suggestionItems.push(
new autocompleteModule.TokenModel(source[i])
);
}
}
console.log("Items for suggestion: " + page.bindingContext.suggestionItems);
然而这种方法不起作用。搜索栏下从未列出任何项目。尽管 console.log() 在 bindingContext 中显示了一个填充良好的 ObservableArray:
Items for suggestion: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
因此,我使用了一个workarround,虽然优雅且不灵活。我在函数范围内填充了一个临时数组,然后我直接使用整个临时数组 set() 绑定上下文中的建议项。
let tempItems = [];
for (let i = 0; i < source.length; i++){
if ( conditionMet(source[i]) ){
tempItems.push(
new autocompleteModule.TokenModel(source[i])
);
}
}
page.bindingContext.set("suggestionItems", new ObservableArray(tempItems));
console.log("Items for suggestion: " + page.bindingContext.suggestionItems);
所以现在如果我想推送一个项目,我需要从头开始替换整个 ObservableArray ......
请注意,对于解决方法,console.log() 输出是相同的。
解决方案
推荐阅读
- machine-learning - 用于 MLP Keras 预测的循环程序
- r - 从 bash 脚本激活 Anaconda?
- python - sklearn shuffle 和 np.random.permutation 的区别
- python - 我如何安排我的功能以使用我制作的这个类?
- python - 无法将表中的所有行作为键,使用 sqlite3 的值
- html - 如何使我的 css 按钮成为 Google 上的这个按钮
- python - 为什么这是以下代码的输出?
- angularjs - 切换路由时如何加载 ng-repeat?
- vue.js - 自定义可见的 vuetify 分页按钮
- c# - File.exists 给出一个空引用异常而不是返回 false。C#