简体   繁体   中英

Knockout subscribe event fired twice

I am using KO observable array and i am trying to change one of its observable field in its own .subscribe method, which causes firing same event twice. How can i avoid this ? Code below

        $.each(self.PricingList(), function (i, pricing) {

        var previousValue = pricing.Currency().code();

        pricing.Currency().code.subscribe(function () {
            ShowConfirmation(null, 'Are you sure ?',
                function () {
                    // will be executed if user click on Yes
                },function () {
                     // Will be executed if user clicks No 
                    // How can i restore previous value ?
                   pricing.Currency().code(previousValue);
                   // the moment i change currency code's value its showing me confirmation dialog again, which i want to avoid.
                });
        });
 $.each(self.PricingList(), function (i, pricing) {    
        pricing.Currency().code.subscribe(function (previousValue) {
            ShowConfirmation(null, 'Are you sure ?',
                function () {

                },function () {
                   pricing.Currency().code(previousValue);// this line calls subscribe method again because the value in this observable changes, so try to remove this line from here.

                });
        }, null, "beforeChange");

Source: http://knockoutjs.com/documentation/observables.html

This isn't directly an answer to your question but I believe it will solve the underlying problem if I have assumed correctly: you are trying to make an optionally-undoable change.

If you look at this blog post it describes an approach where you use a wrapper (similar to an extender) around the observer that provides beginEdit and cancelEdit functions that can be invoked as required.

The source code for this is available in this Github repo .

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