0

我的阵列展出

[
 {"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": ...} 对更改的“访问” ) 而不是整个数组。我不知道该怎么做。

请帮忙。谢谢!

4

1 回答 1

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>
    &nbsp;
    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);
于 2013-06-13T21:31:11.107 回答