当前位置: 动力学知识库 > 问答 > 编程问答 >

How to enable or disable a button using knockout.js

问题描述:

I want to disable a button using knockout.js when the user clicks the button and the server is processing some data. I'm looking at the example in the knockout tutorials but appear to be missing something.

I have the enable: part in the data-bind:

<body>

<form id="form1" runat="server" >

<h1 style="text-align: center">Select the item(s) you want.</h1>

<br />

<br />

<div id="buttons" style="text-align: center">

<button data-inline="true" data-bind="click: submit, enable: canSubmit" >Submit</button>

<button data-inline="true" data-bind="click: cancel">Cancel</button>

</div>

I have set an observable in the view model to false. However, the button is

enabled on the page when the view is initialized. So I think it is a data binding issue.

function ViewModel() {

var self = this;

self.selectedItems = ko.observableArray([]);

// we should start off not being able to click the submit button

self.canSubmit = ko.observable(false);

};

I want to have the button enabled until the user clicks the submit button, then disable it until the server has finished doing it's thing.

self.submit = function () {

// disable submit button

self.canSubmit = false;

// do stuff

self.canSubmit = true;

};

How do you bind the enable observable value to the button?

网友答案:

You're mistakenly replacing your observable with straight js variables. canSubmit is an observable, so change its value by calling the function:

self.submit = function () {
        // disable submit button
        self.canSubmit(false);
        // do stuff
        self.canSubmit(true);
};

The rest is fine as-is.

网友答案:

You're not updating your observable value, you're changing the reference of self.canSubmit so it points to a boolean.

change your self.submit function to:

self.submit = function () {
        // disable submit button
        self.canSubmit(false);
        // do stuff
        self.canSubmit(true);
};
分享给朋友:
您可能感兴趣的文章:
随机阅读: