5

我有一个自定义的 html 元素(一个按钮),我正在向它传递一个方法。然后由自定义元素中的敲除绑定执行。The problem is, I need access to the current object in the array, when selected. 我已经做到了这一点:

ko.components.register('custom-element', {
    viewModel: function(params) {

      this.nestedMethod = function (){
        //this line feels dirty
        var parameter = ko.contextFor(arguments[1].target).$parent;
        params.method(parameter);
      }
    }, 
    template:
    '<button data-bind="click: nestedMethod">remove item</button>'
});

这感觉非常hacky并且可能容易破坏。有没有更好的方法来实现这一点?这是一个工作示例的链接:

http://liveweave.com/w0L5w5

4

2 回答 2

1

由于 Knockout 组件旨在跨页面和视图模型重用,因此它们不应依赖于组件自己的视图模型以外的视图模型。

但是,您可以通过将电流bindingContext作为params对象的一部分传递来访问所需的数据。

例如(在您的 HTML 中):

<custom-element params="method: $parent.removeItem, bindingContext: $context" />

在你的 JS 中:

viewModel: function(params) {
  this.nestedMethod = function (){
    var bindingContext = params.bindingContext;

    // @access using the following:
    // var rootVm = bindingContext.$root;
    // var currentData = bindingContext.$data;
    // var parentData = bindingContext.$parent;

    var parameter = ko.contextFor(arguments[1].target).$parent;
    params.method(parameter);
  }
},
于 2015-04-15T16:57:32.300 回答
0

与其乱搞上下文,不如让父级使用闭包传递对自身的引用。

HTML:

<!-- Note the () in the binding!!! -->
<custom-element params="click: clickHandler()"></custom-element>

JS:

var ParentView = function(message) {
    var self = this;

    self.message = message;

    self.clickHandler = function() {
        return function() {
            alert(self.message);
        }
    }
}

ko.components.register('custom-element', {
    viewModel: function(params) {
        var self = this;

        self.nestedMethod = function() {
            params.click();            
        };
    }, 
    template:  '<button data-bind="click: nestedMethod">remove item</button>'
});

ko.applyBindings(new ParentView("Hello, Knockout!"));

工作JSFiddle

于 2015-04-15T17:15:46.740 回答