Having trouble attaching a function to a button click event

My viewModel includes a function:

 function resetForm(){
        loanSystem("lis");
        status("");
        processor("");
        fileType("funded");
        orderDate("");
        loanNumber("");
        team("");
        borrower("");
        tracking("");
    };

There is a button on the page with:

<button type="reset" data-bind="click: resetForm">Reset</button>

However, I encounter an error message:

Unable to process binding "click: function(){ return resetForm}. resetForm is not defined.

I am sure that my resetForm() function works because it is called in my init function, and any changes made in resetForm() are displayed upon initial page load. Any suggestions?

var homeViewModel = (function () {
    var loanSystem = ko.observable("lis");
    var status = ko.observable("");
    var processor = ko.observable("");
    var fileType = ko.observable("funded");
    var orderDate = ko.observable("");
    var loanNumber = ko.observable("");
    var team = ko.observable("");
    var borrower = ko.observable("");
    var tracking = ko.observable("");
    var isLoanSystem = ko.computed(function () {
        return (loanSystem() == "lps");
    });
    var isCalendar = ko.computed(function () {
        return (isLoanSystem() && fileType() == "cancelled");
    });

    function resetForm(){
        loanSystem("lis");
        status("");
        processor("");
        fileType("funded");
        orderDate("");
        loanNumber("");
        team("");
        borrower("");
        tracking("");
    };

    function submitFileInformation() {
        if (!ValidInputs()) {
            return;
        }
        var fileData = {
            loanSystem: loanSystem(),
            status: status(),
            processor: processor(),
            fileType: fileType(),
            orderDate: orderDate(),
            loanNumber: loanNumber(),
            team: team(),
            borrower: borrower(),
            tracking: tracking()
        };

        $.ajax({
            type: "POST",
            url: "/ComplianceProcessing/Ajax.ashx",
            data: JSON.stringify(fileData),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                if (data === false) {
                    alert("There was an error writing the file to the database.");
                    return;
                }
                alert('Data has been successfully saved.');
                resetForm();
            },
            failure: function() {
                alert('Failure');
            }
        });
    }

    return {
            init: function() {
                resetForm();
            },
            loanSystem: loanSystem,
            isLoanSystem: isLoanSystem,
            status: status,
            processor: processor,
            fileType: fileType,
            isCalendar: isCalendar,
            orderDate:orderDate,
            loanNumber: loanNumber,
            team: team,
            borrower: borrower,
            tracking: tracking
        };
    })(); 

Answer №1

It seems like your resetForm function is not exposed in the viewmodel, making it essentially private and inaccessible to Knockout.

The solution is simple: include the resetForm in your returned object (the "public API") like this:

return {
            init: function() {
                resetForm();
            },
            loanSystem: loanSystem,
            isLoanSystem: isLoanSystem,
            status: status,
            processor: processor,
            fileType: fileType,
            isCalendar: isCalendar,
            orderDate: orderDate,
            loanNumber: loanNumber,
            team: team,
            borrower: borrower,
            tracking: tracking,
            resetForm: resetForm //don't forget to add this line
        };

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

Verify and include phone number entry using Jquery

My input field always requires a + sign to be the first character. HTML <input id="phone"> JS $("#phone").keydown(function (e) { $(this).get(0).value+="+"; // Allow: backspace, delete, tab, escape, enter and . if ($.inArray(e.keyCode, [ ...

Avoiding drag events in hammer.js until the previous event is finished

I've been working on a basic photo gallery that switches images during a drag event. However, I'm encountering an issue with the iOS7 browser where the drag event gets triggered multiple times when dragging left or right. I attempted to use a glo ...

The MDL layout spacer is pushing the content to the following line

Here's an interesting approach to Material Design Lite. In this example from the MDL site, notice how the 'mdl-layout-spacer' class positions elements to the right of the containing div, giving a clean layout: Check it out <!-- Event ca ...

Is there a way to slow down the falling effect on my navigation bar?

As I was working on my personal website, I had a creative idea to add a falling-down animated effect instead of keeping the layout fixed. Utilizing bootstrap for navigation, I encountered some difficulty in controlling the speed of the falling effect. Any ...

"Utilize Node to import either all dependencies or selectively choose specific

Should we only require the specific properties we need or the entire object? Example: Below is a snippet from my helper file 'use strict'; /** * getCallback * return a function used to make callback * @param {callback} callback - the callb ...

Tips on implementing JSON data into select2 plugin

I have been trying to integrate the select2 plugin into my project. I followed a tutorial from this link, but unfortunately, it's not functioning properly for me. Here is the JSON output: [ {"ime":"BioPlex TM"}, {"ime":"Aegis sym agrilla"}, ...

Transferring streaming data from Node.js to an ElasticSearch database

Currently, my Node.js script is extracting data from a large USPTO Patent XML file (approximately 100mb) to create a patentGrant object. This object includes details such as publication number, country, date, and type of patent. I am working on storing a ...

Counting checkboxes in jQuery version 1.9

I recently upgraded my website from jQuery 1.6 to jQuery 1.9.1, and now some of my old code is not working as expected. Specifically, I have a piece of code that handles checkboxes in table rows, allowing only up to 5 checkboxes to be active at once and di ...

There are various iterations of html2canvas available

After upgrading html2canvas from v0.5.0 to v1.0.0, a specific function ceased to work on iOS. Therefore, I am interested in utilizing v0.5.0 on iOS and v1.0.0 on other devices. Is there a way to incorporate and switch between both versions of html2canvas ...

How can JavaScript be integrated with Django static URLs?

I have a Django application where I store static images on Digital Ocean Spaces. Displaying these static images in my template is simple:<img>{% static 'images/my_image.png' %}</img> When I inspect the HTML page after loading, I see ...

Troubleshooting problems with callback functionality in conjunction with Expressjs, JWT authentication, and Angular

For my current project, I am implementing authentication using JWT with Expressjs and Angularjs. However, I now need to integrate node-dbox to access Dropbox files of my users. The issue arises when trying to store the token received from Dropbox for user ...

Anyone able to solve this mysterious CSS alignment problem?

I have a search bar with two image buttons on a webpage I designed using ASP.NET. When I view the page in Internet Explorer 8, Google Chrome or Opera, I noticed that the textbox and image buttons are not aligned properly. The buttons seem to be positioned ...

Using AngularJS to invoke an ASP.NET WebMethod

I have just started learning AngularJS and I'm trying to work on a project. Here is the snippet of HTML code I am working with: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html ...

Navigate through intricate nested JSON array structures in JavaScript

nested json structure Json Tree Structure: { "id": "30080", "dataelements": { "Name": "abc" }, "children": [ { "id": "33024", "dataelements": { "Name": "a" }, "children": [ { "id": "33024", ...

Leverage scope Variable in Angular Service URL

Currently, I am aiming to retrieve data from an API by sending specific search parameters through an AngularJS service. Within my ng-model, I have a variable named "search" that I want to utilize as a parameter in the API URL. My initial (unsuccessful) at ...

Error encountered while parsing JSON data from LocalStorage

Storing an object in localStorage can sometimes lead to unexpected errors. Take this example: function onExit(){ localStorage.setItem("my_object","'" + JSON.stringify(object) + "'"); } When retrieving this data from localStorage, it may loo ...

When outputting the $http response in the console, Angular displays null instead of the expected result,

I have encountered a peculiar issue with my local webservice developed using Spring. Everything seems to be functioning correctly when accessing it through the browser or Postman, but for some reason, when attempting a simple GET method with Angular/Ionic, ...

What is the best way to generate script code dynamically on an HTML page depending on the environment?

I am facing a challenge with my asp.net application. I need to insert a dynamic script into the html section, and this script's value must change depending on the environment (TEST, QA, etc.). To illustrate, here is the script where DisplayValue is th ...

Decode the JSON serialized format generated by CircularJSON

I have a JSON object in my node.js code that contains circular references. To send this information to the browser, I utilized the NPM package circular-json to stringify the object and serialize the circular references: var CircularJSON = require("circula ...

To avoid TS2556 error in TypeScript, make sure that a spread argument is either in a tuple type or is passed to a rest parameter, especially when using

So I'm working with this function: export default function getObjectFromTwoArrays(keyArr: Array<any>, valueArr: Array<any>) { // Beginning point: // [key1,key2,key3], // [value1,value2,value3] // // End point: { // key1: val ...