Having trouble reaching knockout observable from within the confirmation function

I have implemented a Bootstrap confirmation that appears to the user. After the confirmation is clicked, I am trying to access an observable array (this.parameters()) within the same class in the onCancel method. I have tried multiple methods without success. Any assistance would be greatly appreciated.


export class ViewModel {
    
    public parameters: KnockoutObservableArray<Parameter>

    constructor() {

        this.parameters = ko.observableArray(new Array<Parameter>());

        $('div.panel-footer button[data-toggle=confirmation]').confirmation({
            placement: 'top',
            href: '#',
            title: 'Add Parameter',
            btnOkLabel: 'Save & Resend Email',
            btnOkIcon: 'glyphicon glyphicon-envelope',
            btnOkClass: 'btn btn-sm btn-primary',
            btnCancelLabel: 'Save',
            btnCancelIcon: '',
            btnCancelClass: 'btn btn-sm btn-primary',
            onCancel: (e, target) => {
                this.parameters();
            }
        });
    }

Answer ā„–1

The provided example has been created, but unfortunately it seems that it does not fulfill your requirements. Therefore, the issue may lie elsewhere beyond the scope of this demonstration.

Initially, there was speculation about a potential context binding bug with `this`, however, using arrow functions should alleviate any concerns, as demonstrated in the usage of the `confirm` function. To ensure clarity, consider implementing your `onCancel` function similar to how I have done by manually binding your function context. Perhaps this adjustment will enable you to access your class context effectively.

class ViewModel {
  constructor() {

    this.confirm = ko.observable(0);
    this.cancel = ko.observable(0);

    $('#foobar').confirmation({
      onConfirm: () => {
        this.confirm(this.confirm() + 1);
      },
      onCancel: (function () {
        this.cancel(this.cancel() + 1);
      }).bind(this)
    });
  }
}

ko.applyBindings(new ViewModel());
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="12707d7d66616660736252263c243c20">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2a0adadb6b1b6b0a3b282f6ecf4ecf0">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.9.2/umd/popper.min.js" integrity="sha512-2rNj2KJ+D8s1ceNasTIex6z4HWyOnEYLVC3FigGOmyQCZc2eBXKgOxQmo3oKLHyfcj53uz4QMsRCWNbLd32Q1g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap-confirmation2/dist/bootstrap-confirmation.min.js"></script>
<p><button id="foobar">click here</button></p>
<p>confirm: <span data-bind="text: $root.confirm"></span></p>
<p>cancel: <span data-bind="text: $root.cancel"></span></p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am encountering an issue where Typescript paths specified in the tsConfig.app.json file are not resolving properly

I have defined path settings in my tsconfig.app.json file like this: "paths": { "@app/core": ["./src/app/core"] } Every time I run a test that includes import statements with relative paths, it throws the following error: ...

unexpected result from ajax call

After successfully establishing the ajax call, I encountered an issue when trying to retrieve a response from the PHP file. In my .php file, I have <?php echo 'hello'; ?>. However, when I alert the parameter in the success function, it disp ...

Initiate events that are fetched through AJAX requests

Problem: Trouble arises when trying to extract data from an Ajax request that includes components for jQuery functions, and the jQuery functionality fails to work. Resolution: According to Bikash Waiba's response, this issue occurs because the jQuery ...

Trigger a jQuery modal by clicking on a cell within a table

As a novice in jquery, I am facing a challenge. I have a table with a column showing the total number of employees in a department. When a user clicks on this column, it should open up a jquery modal displaying a list of employees like EmpA, EmpB, and Em ...

The loop forEach in ajax is programmed to display only the final record

When making an AJAX request, only the last record from the loop is displayed. See the code snippet below: $.ajax({ method: "POST", url: "{{asset('/num')}}", dataType: "json", ...

Struggling with replacing text in an array using Javascript (Angular)

I am facing an issue where I need to remove the 'hello' substring from each object field in my objects array. However, I keep getting an error message saying "Cannot read property 'indexOf' of null". This error is occurring because I am ...

Issues encountered while parsing JSON data from ajax request in IE8

My jQuery version is 1.8 and I'm working on an ajax call that returns JSON data. In case of an error, it will return { "status": "there was an error" }, otherwise, it will return a document containing the required data like { "document": { ... } } Th ...

Mono repo project utilizing Angular 4+ and Typescript, enhanced with Bootstrap styling

Looking for a project to practice with Angular 4+ using Typescript and a Bootstrap template. Hoping for a setup where I can just run npm install and ng serve to start. Any recommendations for mono repos would be highly valued! ...

Continuously retrieve the value of the selected radio button

After exhausting all options and attempting numerous jquery radio button value checking methods, I still can't seem to find a solution that works for me. Even my own attempted solution didn't pan out. Could someone provide the necessary jquery c ...

What is the best way to trigger one of two different functions randomly when an HTML button is clicked?

Is there a way to have an HTML button trigger one of two functions randomly on click event? Iā€™m utilizing PHP on the server side and jQuery on the client side. I've tried using the following code but nothing happens when I click the button image... ...

Update the document by sending the data and making changes based on the AJAX response

Currently, I am avoiding using jQuery and trying to work with the following code in PHP: <?php header ( 'Content-Type: text/xml; charset=utf-8' ); $con = @mysql_connect ( "localhost", "root", "" ) or die ( "Couldn't connect to database" ...

problem with passing the identification number into the function

I am facing an issue with passing the id into a javascript onClick method. I am using the Spring framework and in the controller class, I send the related id to the JSP file like this: model.addAttribute("uploadid", uploadid); Afterwards, I need to p ...

What term is used to describe this in recursion?

I am trying to understand the concept of reversing a linked list and I stumbled upon a peculiar scenario in which a recursive function doesn't "return" but instead just calls itself. It seems that the function processes data backwards after the recurs ...

How can the HTML source code be printed without showing it in a window or tab?

Here's the scenario: I'm making an ajax post request to a controller action, which returns complete html source code. I want to print this html source as if it were being displayed in a browser without opening a new tab or window. Is there a way ...

Every time I input information into the form, it keeps coming back as undefined

function displayProduct() { var product = document.getElementById("productForm"); var item = product.elements["item"].value ; document.getElementById("outputResult").innerHTML = item ; } <div> <p id="outputResult"></p> </di ...

Troubleshooting issues with executing JavaScript functions during page load

Below is the code snippet I have added at the end of my JavaScript file to test if the functions work upon page load: // Call to load $(document).ready(function() { test(); }ā€‹ And this is what I have at the beginning of my JavaScript file: fu ...

What is the best way to utilize an array variable within another array?

I have two arrays and I want to merge them into one array. However, when I attempt to put one array inside the other, I encounter an issue. var arr=["a","b","c",arr,arr2]; var arr2=["a","b"]; var arr3=[]; arr3=arr[3]; Upon printing out arr, it displays ...

Display a loading screen in ExpressJS until the data is fully loaded and ready for use

I am currently utilizing puppeteer to extract data from a job website, and so far everything is running smoothly. app.get('/', async (req, res) => { res.render('index', {text: 'This is the index page'}); }) Up ...

The upcoming JS/Sass iteration

Today, while working on a portfolio for a friend, everything was running smoothly until I suddenly received an error message stating that sass was not installed, even though I had installed it and been using it all day on port 3000. The error led me into a ...

The persistent loading animation in AngularMaterial Autocomplete does not come to an end

Exploring AngularJS and AngularMaterial: Currently, I am delving into the world of AngularJS and experimenting with AngularMaterial. To put it to the test, I decided to create a sample based on the code provided in the documentation (check codepen). My ap ...