Mapping a single JSON object with Knockout JS made easy

As a newbie to knockout and in the process of creating a jquery mobile app, I'm eager to harness the benefits of knockout. After struggling with a simple issue for a day, I resorted to manually binding code by hand, almost negating the use of KO over jquery. If anyone can guide me on how to leverage the true power of KO, it would be a turning point for me to progress. Most examples I found online were too complex (dealing with arrays, etc.)

The JSON data:

{"id":9,"fullName":"John Doe","firstName":"John","lastName":"Doe","referenceNumber":"BUY-08","position":"Buyer","type":"Buyer","telephone":"028 82 240780","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5c311c3931...">[email protected]</a>","departmentId":3,"departmentName":"DEPT B","country":"United Kingdom"}

The HTML:

<div>
    Full Name: <input data-bind="value: fullName" disabled="disabled"/> <br />
    Ref: <input data-bind="value: reference" disabled="disabled"/> <br />
    Position: <input data-bind="value: position" disabled="disabled"/> <br />
    Email: <input data-bind="value: email" disabled="disabled"/> <br />
    Dept: <input data-bind="value: departmentName" disabled="disabled"/> <br />
    Country: <input data-bind="value: country" disabled="disabled"/> <br />
</div>  

The Javascript:

$(document).ready(function () { 

    function DetailsViewModel() {
        var self = this; 
        self.fullName = ko.observable("");
        self.reference = ko.observable("");
        self.email = ko.observable("");
        self.position = ko.observable("");
        self.departmentName = ko.observable("");
        self.country = ko.observable("");

        var success = function (data) {
            self.fullName(data.fullName);
            self.reference(data.referenceNumber);
            self.email(data.email);
            self.position(data.position);
            self.departmentName(data.departmentName);
            self.country(data.country);
            $.mobile.loading('hide');
        };

        webAPICall("api/user/getcurrentuser",
            "GET", success); // simple wrapper I'm using for ajax calls
    } 
    ko.applyBindings(new DetailsViewModel()); 
});

Any guidance or assistance is highly appreciated. Thank you!

Answer №1

Utilizing a mapping plugin is quite straightforward as long as you do not require any additional functionalities or calculations for your view model. Simply input your JSON data into ko.mapping.fromJS:

var viewModel = {};

function handleSuccess(data) {
    viewModel = ko.mapping.fromJS(data);
    ko.applyBindings(viewModel);
}
webAPICall("api/user/getcurrentuser", "GET", handleSuccess); 

Remember to use fromJS if the data is a JavaScript object and fromJSON if it is a JSON string. Also, ensure that the property names in your data-bind attributes match those in your JSON.

For a demonstration, check out this working example: http://jsfiddle.net/axrwkr/5t5fj/50/

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

Having trouble with jQuery events not triggering properly after dynamically inserting elements using an ajax request?

It's strange that all my jQuery events become unresponsive after an AJAX call. When I use a load function, once the JSP reloads, none of the events seem to work properly. Any suggestions? Below is the code that triggers the function call: $('#p ...

In the production mode, Webpack doesn't compile any code

I recently followed the typescript guide at https://webpack.js.org/guides/typescript/ After running webpack in "production" mode, I noticed that it emitted very minimal output. Below is the code from my src/index.ts file: export function foo() { return ...

The sidebar momentarily shrinks before expanding again when the page is loaded

There is a sidebar on my website that can expand or collapse when a button is clicked. I have successfully saved its state in the localStorage, but there is a small issue that I need help with. When the page loads and there is no saved state in the localS ...

Utilizing a distinct template with ui-router: A step-by-step guide

I am currently working on an Angular application that utilizes ui-router for view routing. Within my master template, I have all the layout elements set up, including my ui-view as shown below: <div class="content" ui-view> <div> Here are my ...

jQuery Ajax comes with a built-in method for validating serialized forms. This method allows

After creating a form and serializing it to send to my MVC Action method, here is how my jQuery Ajax script looks: $('#submit').click(function () { var jsonObj = $('#form').serialize(); alert(jsonObj); $.ajax({ ty ...

Automatically adjusting maps according to internal criteria

I have an example of a map that looks like this const Map = new Map().set('123', [ [ 'foo', 'bar' ] ]).set('456', [ [ 'baz', 'qux' ], [ 'quux', 'corge' ] ]); /* The structure ...

Hiding and showing div elements using CSS, JavaScript, and PHP

Here is the current code snippet: <? while ($row1 = mysql_fetch_object($result1)) { echo '<a href="#" onclick="showhide("'.$row1->id.'");">Name</a>'; while ($row2 = mysql_fetch_object($result2)) { ...

How to retrieve the column names of a table using Web SQL?

Working on extracting column lists from Web SQL (Chrome's local database). One approach is to gather information from sqlite_master. SELECT name, sql FROM sqlite_master WHERE type="table" AND name = "'+name+'"; As an example, here is a sam ...

Unlocking the potential of Vue within shadow dom environments

I am facing an issue with a shadow DOM that includes the root element and a Vue component. <template> <div class="container"> <div id="app"></div> </div> <script src="http://my-site.com/app/js/vue-compo ...

Struggling with the nodejs peepcode tutorial - need some help getting it to run

After purchasing and following the latest nodejs peepcode tutorial, I have hit a roadblock at the initial step. I have spent hours trying to debug my code, but tracing errors in nodejs seems like solving a riddle to me. My app structure is as follows: e ...

Troubleshooting Challenges with JSON and jQuery Encoding

Having an issue with displaying data from a JSON file using jQuery: { "nombre": "Jesús Ramírez", "edad": "25 Años", "imagen":"file.jpg" } Here's my code: JAVASCRIPT $.getJSON(file.json, function(data) { var name= data.nombre; ...

- Question: "Is there a restriction on the size of a JSON array, and if

When attempting to create a JSON array capable of storing 500 JSON objects, everything seems to work fine for the first few records. However, the array is left incomplete after that. JSONArray array=new JSONArray(); for(int g=0;g<500;g++) { JSONOb ...

Retrieve the URI data from the response object using Axios

Currently, I'm in the process of transitioning a node project from utilizing request.js to incorporating axios.js While using the request package, extracting URI data from the response object can be achieved like so: request(req, (err, response) =&g ...

JSON with a null character

Despite spending an hour searching online, I feel a bit hesitant to ask this question. Can null characters (ascii null or \0) be used within JSON? I know they are not allowed within JSON strings, but my query is whether they can be included in the bod ...

Expanding the size of one div causes the surrounding divs to shift positions

I am currently working on creating a row of divs that expand when hovered over by the mouse. I have managed to achieve this functionality, but now I want the expanding div to cover its neighboring divs partially, without affecting their sizes or moving the ...

Retrieve the identification of elements with dynamically generated ids

I've dynamically generated a set of elements using Handlebars, as shown below {{#floor as |room i|}} <div class="btn-group-toggle" data-toggle="buttons" > <label class="btn btn-secon ...

What is the best way to integrate properties subsets into your classes?

In my code, I am working with 3 classes ... class1 { constructor(a, b, c) { this.a = a; this.b = b; this.c = c; this.toClass2 = function() { // TODO: return this as an instance of class2; // the conversion would remove the un ...

How can I use JavaScript to trigger a button click event inside an iframe element

Is there a way to retrieve the inner HTML contents of a clicked element in an iframe loaded content using JavaScript? This code uses jQuery: var elements = document.getElementsByTagName('iframe'); [].forEach.call(elements, function(elem ...

Leveraging current state data (from store) in ReactJS promptly

Working in React with Flux and faced with a challenge. Within my component, I have a function triggered by a click event: onClickEventEdit: function(itemId) { ScheduleActions.getEventById(itemId) // sets the retrieved data into `currentEventById ...

When using the updateMany function, only update the field if it already exists, without creating a new key

My goal within the $set operation is to update a field only if it already exists. While $cond seems to be on the right track, it has the drawback of always creating the field, which is not what I want. Filtering to retrieve only existing fields seems like ...