首页 > 解决方案 > ObservableArray.push() 不通知视图

问题描述

我以这种标准方式在自动完成搜索栏下创建要建议的项目列表:

nativescript-ui 的自动完成组件的屏幕截图 这些项目以 ObservableArray 数据类型列出。

我想通过将它们一一推送到具有条件的 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() 输出是相同的。

标签: javascriptautocompletenativescript

解决方案


推荐阅读