I got stuck trying to implement the Repository-Pattern in Knockout.js. I find it difficult to handle the click event because:
Problems:
- on click: pendDeleteItem is not called. I can not find the scope ;(
- in PendDeleteItem i have a this-Problem. i need to get to the PendingItem property.
working fiddle: /
Goal:
On click the Item gets send to PendingItem.
Restrictions: i want to keep the ko.applyBindings(ViewModel) if possible, because i want to add more Repositoris and define the data-bind in the html like: customer.pendDeleteItem
I got stuck trying to implement the Repository-Pattern in Knockout.js. I find it difficult to handle the click event because:
Problems:
- on click: pendDeleteItem is not called. I can not find the scope ;(
- in PendDeleteItem i have a this-Problem. i need to get to the PendingItem property.
working fiddle: http://jsfiddle/ThomasDeutsch/j7Qxh/8/
Goal:
On click the Item gets send to PendingItem.
Restrictions: i want to keep the ko.applyBindings(ViewModel) if possible, because i want to add more Repositoris and define the data-bind in the html like: customer.pendDeleteItem
Share Improve this question asked Jun 7, 2012 at 8:39 Thomas DeutschThomas Deutsch 2,5642 gold badges28 silver badges36 bronze badges2 Answers
Reset to default 2The first part of your problem is simple. Look at the markup for your button:
<button data-bind"click: $root.customer.pendDeleteItem "> sendTo -> PendingItems</button>
You are missing the =
after the data-bind
attribute name. Change it to this:
<button data-bind="click: $root.customer.pendDeleteItem "> sendTo -> PendingItems</button>
The next problem is that this
in the click handler refers to the "item", not to the view model. You will need to change these lines:
this.PendingItems.push(item);
this.Items.remove(item);
To refer to your view model:
ViewModel.customer.PendingItems.push(item);
ViewModel.customer.Items.remove(item);
Here's an updated fiddle.
For the Second Problem: This Binding will solve it:
data-bind="click: function() { $root.customer.pendDeleteItem($data)}
This is the corresponding js where i can refference this with "this" :)
pendDeleteItem = function(item) {
console.log("pendDeleteItem called");
item.Operation = 'DELETE';
this.PendingItems.push(item);
this.Items.remove(item);
};