简体   繁体   中英

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

You can call both an HTML function and an JS function by wrapping the JS function in the HTML function. The first parameter supplied to the HTML function is the current bound model:

 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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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