如何在按钮的点击功能中获取绑定的可观察内容?

How to get binded observable content inside a click function of a button?

好吧,我在这里遇到了一个棘手的案例,但是为了让每个人都能理解更简单的事情,让我解释一下我的情况。

我在一个循环中有两个按钮,它们分别具有 text:name1text:name2 以及点击绑定。

ViewModel:

           var viewModel = function(){
                var self=this;
                self.arr=ko.observableArray([1]);
                self.name1=ko.observable("click1");
                self.name2=ko.observable("click2");
                self.clickme=function(){
                    console.log(this)
               // this.name1('yoo') this.name1 or name2 should be dynamic based on btn click
               //Here how to access the observanle binded to 'text' for the clicked button
                }
            }
            ko.applyBindings(new viewModel());

单击按钮时,有什么方法可以在我的单击函数中获取单击的按钮 text binded observable,即如果单击按钮 1,我需要在我的函数中 name1

我试过 $element$context 将函数作为参数传递给 VM,但没有解决。

演示 fiddle here

如果对此有任何帮助或想法,那就太好了。

只需将它们传递给函数即可。

<div data-bind="foreach:arr">
    <button data-bind="text:$root.name1,click:function(){$root.clickme($root.name1)}"></button>
    <button data-bind="text:$root.name2,click:function(){$root.clickme($root.name2)}"></button>
</div>

然后像这样在你的视图模型中处理它们:

self.clickme = function (val) {
    alert(val());
}

这是一个modified version of your fiddle.