3

I have a very simple issues, but being new to knockout I'm struggling.

I want to have a few clickable buttons that change css class and send and ajax query when pressed (they can be toggled or not, basically)

Here's my knockout view:

function addStuffViewModel() {
    // Data
    var self = this;
    self.movement = ko.observableArray([
        { name: 'Car', isChecked: false },
        { name: 'Bus', isChecked: false },
        { name: 'Bike', isChecked: false },
         ]);

    toggleButton = function(data,event) {
            data.isChecked = true;
            alert(data.isChecked)
    }    
};

ko.applyBindings(new addStuffViewModel());

And here is the call:

<table style="text-align:center;margin:auto">
    <tr data-bind="foreach: movement">
        <td>
            <a class="btn" style="width:100%;margin:2px" data-bind="text: $data.name,
                                   css: { 'btn-success': $data.isChecked },
                                   click: function(data, event) { toggleButton(data, event) }" /></a>
        </td>
    </tr>
</table>

This alerts the fact that the isChecked has changed, but the observableArray does not register the change. I feel like I want it to be a bit more "magical" than it actually is.

I'm sure it's a grotesque mistake and people will laugh, but any help would be appreciated

4

1 回答 1

3

您想要“监听”的可观察数组中每个对象内部的属性也需要是可观察的。通常,这样做的方法是创建另一个描述这些对象的 ViewModel:

function Item(name, isChecked) {
    this.name = ko.observable(name);
    this.isChecked = ko.observable(isChecked);
}

然后更新您的可观察数组:

self.movement = ko.observableArray([
    new Item('Car', false),
    new Item('Bus', false),
    new Item('Bike', false)]);

示例:http: //jsfiddle.net/CCNtR/25/


您可以通过在以下位置定义toggleButton函数来进一步收紧代码item

function Item(name, isChecked) {
    var self = this;

    this.name = ko.observable(name);
    this.isChecked = ko.observable(isChecked);
    this.toggleButton = function () {
        self.isChecked(true);
    };
}

...然后更新您的视图:

<a class="btn" style="width:100%;margin:2px" 
    data-bind="text: name,
    css: { 'btn-success': isChecked },
    click: toggleButton" /></a>

示例:http: //jsfiddle.net/CCNtR/26/

于 2013-04-26T02:43:21.423 回答