简体   繁体   English

我如何只用一个数据绑定调用2个函数?

[英]How could I call 2 functions with only one data-bind?

I'm trying to make 2 functions run into only one data-bind, but I'm facing some problems because one of this functions is running inside the HTML and I can't change this. 我试图使2个函数仅运行到一个数据绑定中,但是我遇到了一些问题,因为其中一个函数正在HTML内运行,并且我无法更改。 I have google this question and get that: 我有谷歌这个问题,并得到:

click:function(key){text: text}, click:callFunction()

But this isn't working. 但这是行不通的。 The second click bind is working, but the first one no. 第二次单击绑定有效,但第一个没有。

Here's my button: 这是我的按钮:

<button data-bind="attr: {for: 'CC-prodDetails-' + $data.value}, text:key, 
                                                click:function(key){
                                                    $parent.selectedOption(key);
                                                    $parent.selectedOptionValue(key);
                                                }" class="volt"></button>

Here's the function that I need to run: 这是我需要运行的功能:

            changeClass: function () {
            $("button.volt").toggleClass('voltActive');
        },

Someone could help me? 有人可以帮我吗? Put the HTML function inside the other or change it to JS isn't a possibility. 不能将HTML函数放到另一个函数中或将其更改为JS。

You can call both an HTML function and an JS function by wrapping the JS function in the HTML function. 通过将JS函数包装在HTML函数中,可以同时调用HTML函数和JS函数。 The first parameter supplied to the HTML function is the current bound model: 提供给HTML函数的第一个参数是当前绑定模型:

 ko.applyBindings({ myJsFunction: function() { console.log('JS function called'); } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <button data-bind="click: function(model) { console.log('HTML function called'); model.myJsFunction(); }">Click me</button> 

Couldn't you just use the css binding? 您不能只使用css绑定吗?

<button data-bind="
    attr: { for: 'CC-prodDetails-' + $data.value },
    text: key, 
    click: function (key) {
        $parent.selectedOption(key);
        $parent.selectedOptionValue(key);
    },
    css: {
        'voltActive': $parent.selectedOption() === key,
        'volt': $parent.selectedOption() !== key
    }"></button>

Or the class binding that was introduced in 3.5: 或在3.5中引入的class绑定:

class: $parent.selectedOption() === key ? 'voltActive': 'volt'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM