我的阵列正在显示
[
{"name":"Domain Users","access":null},
{"name":"Domain Guests","access":null},
{"name":"Domain Controllers","access":null},
{"name":"Domain Admins","access":null},
{"name":"teachers","access":"1"},
{"name":"SparkUsers","access":null}
]
我的数组是一个可观察的数组,我通过模板预告它。
每次点击,访问值都会更改(null - 0 - 1)
我要做的是,当访问值发生变化时,我希望只能抓取已更改的({“name”:...,“access”:...}对更改“访问”)而不是整个数组。我不知道如何做到这一点。
请帮忙。谢谢!
答案 0 :(得分:1)
我很好奇并提出了这个解决方案(见http://jsfiddle.net/rhp_74/qTema/)
简而言之,您可能想要做的是使access
成为ko.observable
,这样您就可以订阅更改事件并适当地做出反应。
HTML
<div data-bind="foreach: items">
<a href="#" data-bind="text: name, click: changeAccess"></a>
Access: <span data-bind="text:access"></span><br />
</div>
<div data-bind="with: selected">
<h1>Clicked On</h1>
Name: <span data-bind="text: name"></span> <br/>
Access: <span data-bind="text: access"></span> <br/>
</div>
的Javascript
var raw = [
{"name":"Domain Users","access":null},
{"name":"Domain Guests","access":null},
{"name":"Domain Controllers","access":null},
{"name":"Domain Admins","access":null},
{"name":"teachers","access":"1"},
{"name":"SparkUsers","access":null}
];
function ItemViewModel(item) {
var self = this;
this.name = item.name;
this.access = ko.observable(item.access);
this.changeAccess = function() {
self.access(
this.access() == "0" ? "1" :
this.access() == "1" ? null : "0");
};
};
function App() {
var self = this;
this.selected = ko.observable(null);
this.items = ko.observableArray();
for(var i = 0; i < raw.length; i++) {
var item = new ItemViewModel(raw[i]);
item.access.subscribe(function() {
self.selected(this);
}.bind(item));
this.items.push(item);
}
};
var app = new App();
ko.applyBindings(app);