Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout.js : Binding to a function on the click-event using the Repository-Pattern

I got stuck trying to implement the Repository-Pattern in Knockout.js. I find it difficult to handle the click event because:

Problems:

  1. on click: pendDeleteItem is not called. I can not find the scope ;(
  2. in PendDeleteItem i have a this-Problem. i need to get to the PendingItem property.

working fiddle: http://jsfiddle.net/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

like image 387
Thomas Deutsch Avatar asked Mar 11 '26 01:03

Thomas Deutsch


1 Answers

The 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.

like image 170
James Allardice Avatar answered Mar 12 '26 13:03

James Allardice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!