我有一个 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-active
和 date_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/