我正在尝试将单击事件绑定(bind)到列表项。当我单击下面的列表项时,它应该启动 JavaScript 中的 updateCurrent
函数,但它不执行任何操作。
注意:当我调用该函数时,我使用了 $parent.updateCurrent
因为我处于 currentCat
上下文中,并且 updateCurrent
函数是在 ViewModel
上下文中。
HTML:
<div id="wrap" data-bind="with: currentCat">
<div id="names">
<ul data-bind="foreach: $parent.catNames">
<!--Here, clicking on name doesn't fire updateCurrent-->
<li data-bind="text: $data, click: $parent.updateCurrent"></li>
</ul>
</div>
</div>
JS:
var viewModel = function() {
var self = this;
this.catNames = ko.observableArray([]);
this.catList = ko.observableArray([]);
//cats is defined as a simple array of objects, having name
cats.forEach(function(catObject) {
self.catList.push(new cat(catObject));
self.catNames.push(catObject.name);
});
//initially, set the currentCat to first cat
this.currentCat = ko.observable(this.catList()[0]);
//should run when the user click on the cat name in the list
this.updateCurrent = function() {
console.log("hello");
}
};
当我单击列表名称时,我没有收到任何错误,但控制台不记录任何内容。
我相信我没有正确使用上下文,但无法弄清楚这里的确切问题。任何帮助将不胜感激。
最佳答案
当您说 $parent.catNames 时,您指的是 ViewModel,因为它是层次结构中直接父级的拥有属性。通过 foreach 绑定(bind),您将处于一个新的上下文中;因此,在 $parent.updateCurrent 中,层次结构中的直接父级成为 catNames 数组中的项目。
正如 Viktor 所提到的,在这种情况下,您可以使用 $root,但实现此功能的最安全且正确的方法是一次爬上一层以获得 $parents[1]。$parent 等于 $parents[0],它是 catName 之一。 $parents[1] 将引用 ViewModel。
为什么不使用$root?
Knockout 会将您的 DOM 和绑定(bind)上下文维护得比显而易见的更深。在模板绑定(bind)中,$root 上下文可能引用一个甚至不在 HTML 模板中的对象!
<div data-bind="template: { name: 'sample', data: catNames }"></div>
<script type='text/html' id='sample'>
<!-- ko foreach: $data -->
<span data-bind="text: 'Cat ' + $index + ' of ' + $parents[0].length"></span>
Returns "Cat 1 of 10"
<!-- /ko -->
<!-- ko foreach: $data -->
<span data-bind="text: 'Cat ' + $index + ' of ' + $root.length"></span>
Return "Cat 1 of undefined" because ViewModel has no length property!
<!-- /ko -->
</script>
绑定(bind)上下文文档:http://knockoutjs.com/documentation/binding-context.html
关于javascript - knockout 'click' 绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35564379/