KO数组绑定不适用?

时间:2013-04-29 06:26:01

标签: jquery arrays json knockout.js

嗨我似乎遇到了KO数组绑定无法应用的问题..这是我的代码:

var movements_array = [];
var viewModel = { 
    movements: ko.observableArray(movements_array),
};
$(document).ready(function(){
    ko.applyBindings(viewModel);
});

function get_alteration_movement(){

    for(var i = 0; i < index.movements.length; i++)
    {
        movements_array[i] = index.movements[i].description;
        console.log(movements_array);

        viewModel.movements(movements_array);
        console.log(viewModel.movements);
    }

}

索引是从另一个js页面获取的JSON数据。

1 个答案:

答案 0 :(得分:0)

至于我,我通常使用函数而不是对象文字,它更清楚: Difference between knockout View Models declared as object literals vs functions

var viewModel = function(){
    this.movements = ko.observableArray([]);
};

$(document).ready(function () {
    var model = new viewModel();
    ko.applyBindings(model);
    get_alteration_movement(model);
});

function get_alteration_movement(model) {
    var movements_array = [];
    for (var i = 0; i < index.movements.length; i++) {
        movements_array[i] = index.movements[i].description;
        console.log(movements_array);
    }

    model.movements(movements_array);
}