作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我有一个自定义 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 并且可能容易崩溃。有没有更好的方法来实现这一目标?这是一个工作示例的链接:
最佳答案
由于 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/
我是一名优秀的程序员,十分优秀!