1
votes

I have an array exercises inside observableArray workouts. I want to add the ability to remove items from it. Tried to make it an observableArray:

self.exercises = ko.observableArray();

and added a function to remove items:

self.removeExercise = function() {
        self.exercises.remove(this);
    };

But nothing happens. While the same function works with workouts parent array. Along with this I have a simple function for editing items in array, which looks like this:

this.edit = function() { this.editing(true) }

And try to bind it in my View:

<span data-bind="text: name, click: edit"> </span>

but it doesn't work. Where the problem can be?

Here's my View

<div class="content">
    <ul data-bind="foreach: workouts">
        <li>
            <span data-bind="text: name, click: edit"> </span>
                 <a href="#" data-bind="click: $parent.removeWorkout">Remove</a>
             <ul data-bind="foreach: exercises">
                 <li>
                     <span data-bind="text: name"> </span>
                     <a href="#" data-bind="click: $parent.removeExercise">remove</a>
                 </li>
             </ul>
        </li>
    </ul>   
</div>

And ViewModel:

function AppViewModel() {   
    var self = this;

    self.workouts = ko.observableArray([
    {name: "Workout1", exercises:[
        { name: "Exercise1.1" },
        { name: "Exercise1.2" },
        { name: "Exercise1.3" }
    ]},
]);

    self.exercises = ko.observableArray();

    self.removeWorkout = function() {
        self.workouts.remove(this);
    };
    self.removeExercise = function() {
        self.exercises.remove(this);
    };

    this.editing = ko.observable(false);
    this.edit = function() { this.editing(true) }    
}

ko.applyBindings(new AppViewModel);

Here's an example on jsfiddle: http://jsfiddle.net/c9fQB/

Thanks!

1

1 Answers

1
votes

The bindingContext should be $root for removeExercise, and exercises should be an observableArray. Try this: http://jsfiddle.net/Ag8rr/

The observables code:

    self.exercises = ko.observableArray([
        { name: "Exercise1.1" },
        { name: "Exercise1.2" },
        { name: "Exercise1.3" }
    ]);    

    self.workouts = ko.observableArray([
    {name: "Workout1", exercises:self.exercises},
]);