Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout - Cancel a Change Event?

I have a checkbox bound to an observable on a view model. I have a requirement to essentially pop up an "Are you sure?" confirmation prompt if the user changes it from true to false. I'm having a horrible time figuring out the best place to make the change "cancelable" . . .

1) jQuery handler for click event 2) Viewmodel internal subscribe "beforeChange" 3) Viewmodel internal subscribe (normal)

In any case, I'd vastly prefer to have the chance to cancel the change outright than react to the change, potentially reverting it back to its previous value if need be.

Does Knockout's subscribe event give you the chance to cancel a change? Any insight would be appreciated. Thanks!

like image 460
blaster Avatar asked May 14 '12 15:05

blaster


People also ask

What is applyBindings in knockout?

applyBindings method activates Knockout and wires up the view-model to the view. Now that we have a view-model, we can create the bindings. In Knockout.js, you do this by adding data-bind attributes to HTML elements. For example, to bind an HTML list to an array, use the foreach binding: HTML Copy.

How does KnockoutJS work?

KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites. The model separates the application's Model (stored data), View (UI) and View Model (JavaScript Representation of model).

Where is Knockout used?

A knockout (abbreviated to KO or K.O.) is a fight-ending, winning criterion in several full-contact combat sports, such as boxing, kickboxing, muay thai, mixed martial arts, karate, some forms of taekwondo and other sports involving striking, as well as fighting-based video games.

What is Knockout html?

Knockout is a fast, extensible and simple JavaScript library designed to work with HTML document elements using a clean underlying view model. It helps to create rich and responsive user interfaces.


1 Answers

Here is a simple option using jQuery's stopImmediatePropagation:

http://jsfiddle.net/rniemeyer/cBvXM/

<input type="checkbox" data-bind="click: confirmCheck, checked: myvalue" />

js:

var viewModel = {
    myvalue: ko.observable(false),
    confirmCheck: function(data, event) {
        if (!confirm("Are you sure?")) {
            event.stopImmediatePropagation();            
            return false;
        }
        return true;
    }
};
like image 198
RP Niemeyer Avatar answered Sep 22 '22 13:09

RP Niemeyer