【问题标题】:Knockout: passing the current object to a method through a custom elementKnockout:通过自定义元素将当前对象传递给方法
【发布时间】:2015-04-15 16:31:35
【问题描述】:

我有一个自定义的 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

【问题讨论】:

  • 用你需要的所有东西构建一个组件......不仅仅是按钮。它会更容易(我猜)维护并且不会那么麻烦(无论如何,您正在使用客户端阵列,尝试保护它们很困难)。不要使用全局数组(只在其私有范围内使用)

标签: javascript knockout.js custom-element


【解决方案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);
  }
},

【讨论】:

    【解决方案2】:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-17
      • 2019-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多