【问题标题】:How to get binded observable content inside a click function of a button?如何在按钮的单击功能中获取绑定的可观察内容?
【发布时间】:2015-03-17 00:18:48
【问题描述】:

好吧,我在这里遇到了一个棘手的情况,但为了让大家更容易理解,让我解释一下我的情况。

我在循环中有两个按钮,分别绑定 text:name1 和 text:name2 和点击绑定。

视图模型:

           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 的函数,但没有解决。

演示小提琴here

对此的任何帮助或想法都会很棒。

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    只需将它们传递给函数。

    <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.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      • 1970-01-01
      • 2016-11-13
      相关资源
      最近更新 更多