Exploring data segments in Knockoutjs using various models

I'm trying to figure out why Knockout.js won't allow me to access specific parts of the model data. Could it be because I am binding the model to the div that contains all the submodels (such as the Form in this example), or am I approaching this incorrectly?

For instance, in this JSFiddle http://jsfiddle.net/zv6hauft/1/

I want to only save fare information and exclude bus information. However, even when I pass "fare_lines" in the example, it displays all models in the console.

<!doctype html>
<script src="/javascript/knockout-3.3.0.js"></script>
<form id="transport_form" method="post">
    <table class="table table-condensed required" data-bind='visible: bus_lines().length > 0'>
        <thead>
            <tr>
                <th>Bus</th>
            </tr>
        </thead>
        <tbody data-bind='foreach: bus_lines'>
            <tr>
                <td>
                    <input name="bus_date" type="text" class="bus_date" value=" " data-bind='value: bus_desc' required/>
                </td>
                <td><a href='#' id="bus_remove" data-bind='click: $parent.removeBusLine'>Delete</a>
                </td>
            </tr>
        </tbody>
    </table>
    <div class="controls">
        <button id="bus_button" data-bind='click: addBusLine'>Add Bus</button>
    </div>
    <div id="fare_info_table">
        <table data-bind='visible: fare_lines().length > 0'>
            <thead>
                <tr>
                    <th>Fare</th>
                </tr>
            </thead>
            <tbody class="table required" data-bind='foreach: fare_lines'>
                <tr>
                    <td>
                        <input id="fare_amnt" data-bind='value: fare_desc' required />
                    </td>
                    <td><a href='#' id="fare_remove" data-bind='click:$parent.remove_fare_line'>Delete</a>
                    </td>
                </tr>
            </tbody>
        </table>
        <div class="controls">
            <button id="fare_button" data-bind='click: add_fare_line'>Add fare</button>
        </div>
    </div>
    </br>
    </br>
    <div class="control-group">
        <div class="controls">
            <button type='submit' data-bind="click: save_record">Submit</button>
        </div>
    </div>
</form>

</html>



<script>


//Bus Model
var Bus_model = function () {
    var self = this;
    self.bus_desc = ko.observable();
};



var fare_model = function () {
    var self = this;
    self.fare_desc = ko.observable();
}

var operations_bus_fare = function () {

    var self = this;

    //Study Schedule Operations
    self.bus_lines = ko.observableArray([new Bus_model()]);
    self.addBusLine = function () {
        self.bus_lines.push(new Bus_model())
    };
    self.removeBusLine = function (Bus_line) {
        self.bus_lines.remove(Bus_line)
    };

    //Fare operations
    self.fare_lines = ko.observableArray([new fare_model()]);
    self.add_fare_line = function () {
        self.fare_lines.push(new fare_model())
    };
    self.remove_fare_line = function (fare_line) {
        self.fare_lines.remove(fare_line)
    };




    self.save_record = function (fare_lines) {
        var saveData2 = ko.toJSON(fare_lines);
        console.log(saveData2);
        alert(saveData2);
    };
};

ko.applyBindings(new operations_bus_fare(), document.getElementById("transport_form"));

</script>

Answer №1

To access a portion of the ViewModel, you can follow this approach

ViewModel:

self.save_record = function (data) { // receiving entire vm here as parameter
    var saveData2 = ko.toJSON(data.fare_lines); // accessing the necessary part 
    console.log(saveData2);
    alert(saveData2);
};

Check out the working example here

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

The technique of binding methods in React

When working with React.js, it's recommended to define your method binding in the constructor for better performance. Here's an example: constructor(props){ this.someFunction = this.someFunction.bind(this); } This approach is more efficient t ...

What is the technique for extracting data from a Firebase application after a user has successfully logged in?

I'm currently facing an issue with my website's forum, which is integrated with Firebase for storing forum posts and user login information. The challenge I'm encountering involves retrieving data from the logged-in user's child in orde ...

Avoiding the issue of multiple submissions in Ajax forms

My website's contact form sometimes experiences a delay in sending submissions. When users, in their impatience, click the submit button multiple times, it results in the form being sent repeatedly to the host. To address this issue, I attempted to ...

Directive not working on Mozilla Firefox

Currently, I have a directive set up to display an image as a background image. This works perfectly fine in Chrome and Safari, but for some reason, it doesn't seem to be functioning properly in Firefox as the background images are not showing up. Aft ...

Verify whether the input field contains a value in order to change certain classes

My meteor-app includes an input field that dynamically changes position based on whether it contains content or not. When a user begins typing, with at least one character, the input field moves to the top of the page. In my current approach, I am using a ...

Navigating back to the app after saving contacts can be achieved using React Native and the react-native-contacts library

I am currently utilizing the react-native-contacts library in my React Native application to save a contact. Prior to saving the contact, I request WRITE permission from Android. The process is successful; I open the contact form within my app and proce ...

Encountering a problem when verifying if the data is in JSON format using JavaScript

I'm using JavaScript to determine whether an input value is in JSON format, but I've encountered a problem with a specific value. Below is my code explanation. isJSON = async(str) => { try { return (JSON.parse(str) && !!str); ...

I'm encountering an issue in JavaScript while attempting to convert the following string into a JSON object. Can anyone assist in identifying the problem with this string?

How can I correct this string to make it a valid JavaScript JSON object? txt = '{"Categories" : [{"label":"petifores","id":"1"}, {"label":"wedding cake","id":"2"}, {"label":"shapes of cakes","id":"3"}, ...

How to Target HTML Tags Locally using CSS Modules in Next.js?

I am looking to implement smooth scrolling specifically on one page in my Next.js application, such as my blog. Instead of applying it to the entire site through the globals.css file, I need a way to inject scroll-behavior: smooth; into the html tag only f ...

Toggle class on child element when parent is clicked

I am currently working on a functional React component that looks like this: const RefreshButton = () => ( <IconButton> <RefreshIcon /> </IconButton> ) My goal is to dynamically assign a class attribute ...

Steps for adjusting the length in the getRangeLabel function of mat paginator

@Injectable() export class MyCustomPaginatorIntl extends MatPaginatorIntl { public getRangeLabel = (page: number, pageSize: number, length: number): string => { if (length === 0 || pageSize === 0) { return `${ ...

Retrieve the identification number from the code snippet containing the "append(<tr><td="ID">..." template

I have a table that I'm populating with data from a firebase database using the append() function. $("#table_body").append("<tr><td>" + name + "</td>" + "<td>" + brand + "</td>" + ...

Storing an array within an AngularJS service for better performance

As someone who is relatively new to AngularJS, I am still in the process of understanding how to utilize services for fetching data in my application. My aim here is to find a method to store the output of a $http.get() call that returns a JSON array. In ...

How can union types be used correctly in a generic functional component when type 'U' is not assignable to type 'T'?

I've been researching this issue online and have found a few similar cases, but the concept of Generic convolution is causing confusion in each example. I have tried various solutions, with the most promising one being using Omit which I thought would ...

The integration of signalR with jquery mobile is posing several challenges

Recently, I started working with jquery mobile and signalR to implement a calling feature in my mobile app. However, I encountered an error that looks like this: http://localhost:2286/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%2 ...

When using Vue3 along with Axios.post, the data is being serialized incorrectly

Goal: I need to send the data {"username": myuser, "password": mypswd} to an API endpoint in order to receive a token for further communication with the API. The following code snippets attempt to achieve this: // Attempt # 1 let re ...

When attempting to validate dates with the after: rule in vee-validate while also utilizing a computed field in Vue.js, the validation process may encounter unexpected issues

Below is a codepen with a simple input field for entering dates: <input type="text" v-model="startDate" name="StartDate" v-validate="{ required: false, date_format: 'dd/MM/yyyy', before: maxStartDate }"/> Despite e ...

Toggling the visibility of divs in a dynamic layout

How can I use JQuery/JavaScript to show only the comment form for a specific post when a button or link is clicked on a page containing multiple posts divs with hidden comment forms? <div class="post"> <p>Some Content</p> <a ...

Implementing automatic selection mode in Kendo MVC grid

Seeking to modify the SelectionMode of a Kendo MVC Grid, I aim to switch from single to multiple using Javascript or JQuery upon checkbox selection, and revert back when the checkbox is unchecked. Is this feasible? Additionally, I am successfully binding a ...

What is the best way to utilize the each method within jQuery plugins?

I am relatively new to JavaScript and jQuery plugin development, so please bear with me if this question seems silly. I am struggling with a particular aspect of the following plugin script: (function($){ $.fn.test = function(){ var containe ...