"Creating a function within a knockout viewmodel that is populated with JSON data: A step-by-step guide

Struggling with defining a function inside my viewmodel.

I retrieve json data using jquery getJSON and then map it to the viewmodel.

$.getJSON('/Company/GetCompanies', function(data) { 
    var viewModel = new CompanyViewModel()
    viewModel.model = ko.mapping.fromJS(data)
    ko.applyBindings(viewModel)
});

Here is the viewmodel. The goal is to extract one of the properties of the viewmodel using a function called companyName

var CompanyViewModel = function() {
    var self = this;

    self.companyName = function() {
         return model.CompanyName; 
    };
}

Then I aim to utilize this function like

<span data-bind="text: companyName" />
However, the JavaScript function doesn't seem to be evaluated correctly and ends up being displayed as text.

Reviewed numerous Knockout examples online, but they all rely on computed observables.

Is there a way to achieve this? Much appreciated.

Answer №1

Check out this solution:

let BusinessViewModel = function(data) {
    ko.mapping.fromJS(data, {}, this); 
};

BusinessViewModel.prototype.payTaxes = function() {
    console.log("Business is paying its taxes.");
};

$.getJSON('/Business/GetInfo', function(data) { 

    // data structure would be something like:
    // data: { businessName : "Google",
    //         ownerName : "etc" }
    
    let view = new BusinessViewModel(data);
    ko.applyBindings(view)
});

Answer №2

After conducting some tests, I have found a successful solution:

return self.model()[0].CompanyName;

To call the above code, use: data-bind="text: companyName()"

UPDATE:

       var CompanyViewModel = function() {
            var self = this;

            self.companyName = function(){

                 return self.model()[0].CompanyName; 
            };
        }

        $.getJSON('/Company/GetCompanies', function(data) { 
            var viewModel = new CompanyViewModel();
            viewModel.model = ko.mapping.fromJS(data);
            ko.applyBindings(viewModel);
        });

This method relies on the assumption that your JSON data is structured as follows:

[{"CompanyName":"Stack","SomeOtherField":"SomeOtherValue"},...];

Additionally, it assumes there is only one company listed in the data.

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

Managing environment variables in a production server with Webpack post continuous integration can be done in a couple of ways

I am currently working on deploying a ReactJs application in production using Webpack as my build tool. To set environment variables, we are utilizing the DefinePlugin feature. new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify( ...

The correct way to create a Reaction Collection

I'm trying to set up an event where a user triggers a reaction with either a Check mark or X. However, I keep encountering an error that the function doesn't exist for the message object. I attempted to switch back to awaitReactions but it didn& ...

Bring in multiple classes from node_modules

During the development of my package, I have organized my repository with the following structure: src - Requests.js - Constants.js package.json The package.json file contains the following information: { "name": "package-name", "version": " ...

What is the reason behind Typescript flagging a potential undefined value when checking for array length using a greater than comparison but not with an

Consider the following excerpt from a React component: const AccountInformation = (props: { readonly accountData: AccountData | undefined | null }) => { const hasMultipleAccounts: boolean = props.accountData?.customerAccounts?.length === 1 ? false : t ...

Exploring the implementation of waterfall in a Node.js application

async.traverse(map, function(item, tnext){ async.waterfall([ function(wnext){ console.log("One"); //performing MongoDB queries db.collection.find().toArray(function(err){ if(err){ ...

Ajax - Trouble with Updating DIV Content

As a beginner in AJAX, I am encountering difficulties creating a simple AJAX program. My goal is to have a button that, when clicked, changes the text of the div below it. Despite numerous attempts, I have not been able to identify the issue. Below is the ...

Refresh the information displayed in the HTML table

I've been assigned the task of developing a shift management web app to help our current employees track their shifts. The website StaffHub has been suggested as a reference for my web app, and I am currently focused on implementing the calendar featu ...

Generate a new JSON reply using the current response

I received a JSON response that contains values for week 1, week 2, week 3, and week 4 under the 'week' key, along with counts based on categories (meetingHash) and weeks. I attempted to merge this data using the .reduce method but without succes ...

"Send the response in ExpressJS before making a request to loop through the

I am currently working with a postgres database that contains records with a column format in JSON, which refers to other similar records. The challenge I am facing is retrieving linked records through asynchronous methods due to the nested structure and ...

The integration of query, URL, and body parameters is not working as expected in Seneca when using Seneca

I'm facing some difficulties with Seneca and seneca-web as a beginner. This is the current state of my code: "use strict"; var express = require('express'); var Web = require("seneca-web"); var bodyParser = require('body-parser' ...

Django plugin designed for showing a real-time feed of messages - powered by Dajax or Jquery?

Currently, I am attempting to set up a section in my Django application where updates or messages from the server can be displayed once specific tasks are done. I had initially looked into using a plugin that utilizes Dajax / Jquery for this feature, but ...

In JavaScript, when a condition is met, two strings are produced but only the last string is printed

My for loop with nested arrays is working fine, but it should display two strings and only shows the last one. for (i = 0; i < $scope.taskGroups.length; i++) { for (j = 0; j < $scope.taskGroups[i].tasks.length; j++) { ...

InvalidSyntaxError: Client login cannot be completed due to an unexpected end of input. Please

I encountered an issue while trying to create a bot that sends welcome messages for my friend's server. Despite numerous attempts to troubleshoot the problem within my code, I have been unable to resolve it. Any assistance in solving this error would ...

Issues with Toggling Visibility in HTML, CSS, and Javascript

Currently, I am working on a website and following a tutorial called "Creating Slideshow using HTML, CSS, and Javascript" by W3Schools. In the project, I want to hide the thumbnail images located at the bottom and the navigation arrows initially and have t ...

Parse a string in the format of "1-10" to extract the numbers and generate an array containing the sequence of numbers within the range

Looking to convert a string in the format "1-10" into an array containing the numbers within that range. Display the array on the screen using a for loop. For example, if "1-5" is provided, the resulting array should be: {1, 2, 3, 4, 5} Create a workflow ...

Utilizing the body in GET requests for enhanced client-server communication

What makes url query strings better than request body values? There are distinct advantages to using url parameters, such as visibility in the address bar and the ability to save requests in the browser history. However, is there more to it? Could reques ...

How can I replicate the functionality of a div mimicking a select element using javascript upon clicking away from the element?

My task was to design a pseudo-select element that showcases columns for each row within the select. Due to HTML's restriction on allowing the <option> tag to include HTML, I had to find an alternate solution. One issue I encountered was replic ...

Increase the options available in the dropdown menu by adding more selected items, without removing any already selected

I came across this code on the internet http://jsfiddle.net/bvotcode/owhq5jat/ When I select a new item, the old item is replaced by the new item. How can I add more items without replacing them when I click "dropdown list"? Thank you <select id=&qu ...

Issue with adding HTML content to bootstrap modal not functioning as expected

Having trouble displaying an image in a bootstrap modal by using data- attribute within a php foreach loop. The image doesn't seem to appear in the target div. Here's my code snippet: <script> $(document).ready(function(){ $( ".subscri ...

Managing object methods in ReactJS state

Currently, I am utilizing the Google Maps API and have the following piece of code implemented: class App extends React.Component { state = { polygon: null, }; checkPoly() { if (this.state. ...