javascript - 如何更新 knockoutjs 可观察数组项

标签 javascript knockout.js

我有一个 View 模型设置,其中包含可观察的用户对象数组。添加/删除项目工作正常,但如何更新项目?我可以使用 ko indexOf 函数找到这些值。

function User( username, date_inactive, date_active ) {
    this.username = username;
    this.date_active = date_active;
    this.date_inactive = date_inactive;
};  

User.prototype.inactivateMe = function() {
    json_responses.push( this );
    $.getJSON( "url" + this.username, function( json ) {
        original = json_response.pop();
        //do update here
    });
};

userModel = [  ], //Where the loaded usernames are stored. 

viewUserModel = {
    users: ko.observableArray(userModel)
    //.......

    //This is how I'm adding users to the array.
addUser: function () {
    $.getJSON( "url", 
    { username: usern }, 
        function( json ) { 
            if( json.STATUS != undefined && json.STATUS == 'success' ) {
                newuser = new User( json.USERNAME, json.DATE_ACTIVE, json.DATE_INACTIVE  );
                viewUserModel.users.push( newuser );            
            }
        }
    });
    }

viewUserModel.users 的值从服务器 json 响应推送到数组中。

我希望能够在用户单击按钮且服务器成功响应时更新 date_active 和 date_inactive 值。

我的设置改编自 http://net.tutsplus.com/tutorials/javascript-ajax/into-the-ring-with-knockout-js-the-title-fight/

最佳答案

可观察数组仅跟踪对数组所做的更改(例如推送和弹出),而不跟踪数据本身。您需要按照 @Ianzz 指定的方式创建 date-activedate_inactive observables。

function User( username, date_inactive, date_active ) {
    this.username = username;
    this.date_active = ko.observable(date_active);
    this.date_inactive = ko.observable(date_inactive);
};

然后在您的 html 中执行以下操作

<div data-bind="foreach: Users">
    <input data-bind="value: date_active"/>
    <input data-bind="value: date_inactive"/>
<div>​

参见fiddle完整示例。

关于javascript - 如何更新 knockoutjs 可观察数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12609597/

相关文章:

javascript - Angular 2-way 绑定(bind)不起作用,但表达式起作用

javascript - 忽略 moment.js 的 eslint 错误

javascript - 如何在 devexpress 和 knockout.js 中格式化日期并将其插入数据库?

events - 使用映射插件时,Knockout 中的 beforeChange 值未定义

javascript - knockout : Order of the bindings evaluation when using click and checked bindings in the same time

javascript - 从 Callback hell 转换为 Promise

JavaScript:数组。为什么将一个空数组与一个填充数组连接起来会产生一个字符串?

javascript - Redux 在功能组件中分派(dispatch)后没有立即更新

javascript - 如何在 knockout.js 中检查值是否为 NULL 或未分配?

javascript - 使用普通变量为 knockout js 设置 css 属性