【发布时间】: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并且可能容易被破坏。有没有更好的方法来实现这一点?这是一个工作示例的链接:
【问题讨论】:
-
用你需要的所有东西构建一个组件......不仅仅是按钮。它会更容易(我猜)维护并且不会那么麻烦(无论如何,您正在使用客户端阵列,尝试保护它们很困难)。不要使用全局数组(只在其私有范围内使用)
标签: javascript knockout.js custom-element