gpt4 book ai didi

javascript - knockout : passing the current object to a method through a custom element

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:31:13 24 4
gpt4 key购买 nike

我有一个自定义 html 元素(一个按钮),我正在向其传递一个方法。然后由自定义元素中的 knockout 绑定(bind)执行。问题是,我需要在选择时访问数组中的当前对象。我是这样实现的:

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

最佳答案

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

但是,您可以通过将当前 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);
}
},

关于javascript - knockout : passing the current object to a method through a custom element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29655819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com