gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 22:20:38 25 4
gpt4 key购买 nike

我有一个 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 observable。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com