简体   繁体   中英

How to use jquery ui button with knockout?

I have the following html:

<button id="simpleBtn" data-bind="jqButton: true, click: runTest, style: {backgroundColor: color}">Click me</button>

and the following model:

function Test(testName, test) {
            var vm = {};

            vm.result = ko.observable(false);
            vm.testName = testName;
            vm.color = ko.computed(function (){
                return vm.result() === true ? 'green' : 'red';
            }, vm);

            vm.test = test;
            vm.runTest = function () {
                var result = vm.test();
                vm.result(result);
            }

            return vm;
        }

        ko.bindingHandlers.jqButton = {
            init: function (element) {
                $(element).button();
            }
        }

        ko.applyBindings(Test('Name', function () {
            //test code
        }));

I want to change the style of button, but this code doesn't work. What should I do to make it work?

How about using the css binding instead? Here's an updated fiddle

<td><button id="testBtn" data-bind="jqButton: {enable: true}, click: runTest, css: StyleRunTest">Run test</button></td>

function applyKnockoutModel() {
    function Test(testName, test) {
        var vm = {};
        vm.StyleRunTest = ko.observable('btn-valid');
        vm.result = ko.observable(false);
        vm.testName = testName;
        vm.color = ko.computed(function () {
                return vm.result() === true ? vm.StyleRunTest('btn-valid') : vm.StyleRunTest('btn-invalid');
            };
        };
    };
};

It must be an issue with the order of loading scripts. Check your console for errors. Your code works here jsfiddle.net/zA7L3/

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