Reputation: 7505
All the data displaying and adding / deleting buttons seem to work until I change the delete button to do a check to make sure that there is always at least one person on the screen:
<!-- Check number of items before enabling delete button !-->
<button type="button" data-bind='enable: people().length > 1, click: $root.removePerson'>Delete</button>
The error is as follows:
Uncaught ReferenceError: Unable to process binding "foreach: function (){return people }"
Message: Unable to process binding "enable: function (){return people().length > 1 }"
Message: people is not defined
HTML
<div data-bind='foreach: people'>
<div class="personWell">
<input type="text" data-bind="value: name"></input>
<input type="text" data-bind="value: company"></input>
<button type="button" class="btn btn-sm btn-warning" data-bind='click: $root.removePerson'>Delete</button>
</div>
</div>
<button type="button" class="btn btn-sm btn-primary" data-bind='click:addPerson'>Add Person</button>
JavaScript
var ObservedPersonModel = function(people) {
var self = this;
self.people = ko.observableArray(people);
self.addPerson = function() {
self.people.push({
person_id:"",
name: "",
company: "",
positive_observation_id:""
});
};
self.removePerson = function(person) {
self.people.remove(person);
};
};
//originalPeopleObserved is a JSON encoded list of objects
var peopleViewModel = new ObservedPersonModel(originalPeopleObserved);
ko.applyBindings(peopleViewModel);
Resources
Here are some of the links where I learned about this functionality:
Upvotes: 1
Views: 999
Reputation: 3160
Actually i got your code running in a fiddle. First thing i changed was two >
you forgot in your html code:
<input type="text" data-bind="value: name"></input>
<input type="text" data-bind="value: company"></input>
Then i added an empty object for testing:
originalPeopleObserved = null;
var peopleViewModel = new ObservedPersonModel(originalPeopleObserved);
ko.applyBindings(peopleViewModel);
And on Safari i can use your sample as expected. Try this fiddle here
Upvotes: 0
Reputation: 528
Try this:
<button type="button" data-bind='enable: $root.people().length > 1, click: $root.removePerson'>Delete</button>
Upvotes: 1