[英]knockout 'click' binding not working
我試圖將click事件綁定到列表項。 當我單擊下面的列表項時,它應該啟動javascript中的updateCurrent
函數,但不會執行任何操作。
注意:調用函數且updateCurrent
函數位於ViewModel
上下文中時,我在currentCat
上下文中使用了$parent.updateCurrent
。
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綁定,您將處於一個新的上下文中; 因此,在$ parent.updateCurrent中,層次結構中的直接父級成為catNames數組中的項。
在這種情況下,您可以使用$ root,正如Viktor提到的那樣,但是實現此功能的最安全正確的方法是一次將層次結構爬上一層以獲得$ parents [1]。
$ parent等於$ parents [0],它是catNames之一。 $ parents [1]將引用ViewModel。
為什么不使用$ root?
淘汰賽將使您的DOM和綁定上下文保持得比可能顯而易見的更深。 在模板綁定中,$ 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>
綁定上下文文檔: http : //knockoutjs.com/documentation/binding-context.html
您處於兩個級別的上下文中。 with
綁定表示該div
中的$data
是currentCat
。 foreach
提供了另一個層次的上下文。 $parent
不是引用對象的父對象,而是引用該上下文之外的上下文。 您可以使用$parents[1]
。
當您說$parent.catNames
,您僅位於with
上下文中,因此它確實引用了ViewModel
catNames
,因為沒有其他封閉的上下文。 但是在說$parent.updateCurrent
,您會從foreach
上下文跳到with
上下文。 您想再跳一跳。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.