Pregunta

I have 3 list items that use a foreach binding. I would like for it to toggle to an 'activeClass' when I click one of them.

This is what I have so far! Your help is much appreciated.

<h4>People</h4>
 <ul data-bind="foreach: people">
<li>
    <span data-bind="text: name, css: function () { $root.styling(); }, click: function    () { $root.toggle();}"> </span>
</li>
</ul>

function AppViewModel() {
var self = this;
self.active = ko.observable(false); 
self.people = ko.observableArray([
    { name: 'Bert' },
    { name: 'Charles' },
    { name: 'Denise' }
]);
self.styling = ko.computed(function () {

    if (self.active() === true) {
        return 'activeClass';
    }
    else {
        return '';
    }
});

self.toggle = function () {
    self.active(!self.active());

}
}
ko.applyBindings(new AppViewModel());

http://jsfiddle.net/s3kg9/5/

¿Fue útil?

Solución

You need to add active as part of each object and make it observable, then pass it to the function: JsFiddle

The Html part:

<h4>People</h4>
<ul data-bind="foreach: people">
    <li>
        Name at position <span data-bind="text: $index"> </span>:
        <span data-bind="text: name, css:  $root.styling($data), click: function () { $root.toggle($data);}"> </span>
    </li>
</ul>

And the ViewModel:

function AppViewModel() {
    var self = this;
    self.people = ko.observableArray([
        { name: 'Bert', active: ko.observable(false) },
        { name: 'Charles', active: ko.observable(false) },
        { name: 'Denise', active:ko.observable(false) }
    ]);
    self.styling =function (person) {
        if (person.active() === true) {
            return 'test';
        }
        else {
            return '';
        }
    };

    self.toggle = function (person) {
       person.active(!person.active());      
    }

}

ko.applyBindings(new AppViewModel());
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top