将数组转换为可观察数组

时间:2014-04-26 00:11:23

标签: knockout.js observable

有没有办法将observable转换为可观察数组?

我问这个是因为我的代码中有一个函数需要可观察数组,因为函数使用ko.utils.arrayForEach

我试着谷歌但却找不到任何东西。

更新

我使用var test = isObservable(item)检查了我传递的内容。我没有观察到我正在传递,因为我在变量test它的正常数组中得到了错误。

所以我想将数组转换为可观察数组

2 个答案:

答案 0 :(得分:1)

这个问题对我来说并没有多大意义,但这里有 -

要将数组转换为可观察数组,请执行此操作 -

var normalArray = ['1', '2']
normalArray = ko.observableArray(normalArray);
// normalArray is now an observableArray

答案 1 :(得分:0)

您可以使用ko.observableArray()

将convert normal数组转换为可观察数组
var SimpleListModel = function(items) {
    this.items = ko.observableArray(items);
    this.itemToAdd = ko.observable("");
    this.addItem = function() {
        if (this.itemToAdd() != "") {
            this.items.push(this.itemToAdd()); // Adds the item. Writing to the "items" observableArray causes any associated UI to update.
            this.itemToAdd(""); // Clears the text box, because it's bound to the "itemToAdd" observable
        }
    }.bind(this);  // Ensure that "this" is always this view model
};

ko.applyBindings(new SimpleListModel(["Alpha", "Beta", "Gamma"]));

工作示例http://jsfiddle.net/rniemeyer/bxfXd/

相关问题