【问题标题】:How to get reference to the ViewModel within a foreach data-bind?如何在 foreach 数据绑定中获取对 ViewModel 的引用?
【发布时间】:2015-08-20 10:27:50
【问题描述】:

在我的 ViewModel 中,我有一个可观察的数组,这个数组的一个元素可以是选定的元素:

var ViewModel = function () {

// the array
this.fruits = ko.observableArray([{
    name: "apple"
}, {
    name: "orange"
}, {
    name: "banana"
}]);

// the selected element
this.selectedFruit = null;

};

ko.applyBindings(new ViewModel());

现在我在列表中显示元素:

<div data-bind="foreach: fruits">
<ul>
    <li href="" data-bind="text: name "></li>
</ul>

现在我希望单击一个项目可以在我的 ViewModel 中选择选定的水果。这样做的 KnockoutJS 方式是什么?如何在 foreach 循环中创建一个函数来引用回水果?

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    您需要返回父级执行该方法,因为您当前的作用域在水果数组内。代码如下所示:

    <div data-bind="foreach: fruits">
    <ul>
        <li href="" data-bind="text: name, click: $parent.fruitWasClicked"></li>
    </ul>
    </div>
    
    
    this.fruitWasClicked = function(fruit){
    //do something here
    }
    

    这里是一些进一步解释上下文的文档 http://knockoutjs.com/documentation/binding-context.html

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 2021-10-07
    • 1970-01-01
    • 2012-04-05
    • 2018-05-17
    • 2021-12-25
    • 1970-01-01
    相关资源
    最近更新 更多