最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin6浏览0评论

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: /

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:

  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/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 badges
Add a ment  | 

2 Answers 2

Reset to default 2

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.

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);
    };
发布评论

评论列表(0)

  1. 暂无评论