Exploring the Concept of Nested ViewModels in Knockout.js Version 3.2.0

I have a global view model that is applied to the main div

and I also have other view models that I want to apply to nested elements within my main div

However, I am encountering an issue:

You cannot bind multiple times to the same element.

Below is a sample of the code causing the problem:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>

    <div id="main">

        <input data-bind="value:title,valueUpdate:'afterkeyup'" />

        <h1 data-bind="text:title"></h1>


        <hr />

        <div id="sub">

            <input data-bind="value:name,valueUpdate:'afterkeyup'" />
            <label data-bind="text:name"></label>

            <!-- a reference to title in globalViewModel -->
            <h1 data-bind="text:title"></h1>

        </div>

    </div>

    <script src="Scripts/knockout-3.2.0.js"></script>
    <script>

        var globalViewModel = {
            title : ko.observable("global title")
        }

        var subViewModel =  {
            name : ko.observable("Test")
        }

        ko.applyBindings(globalViewModel);
        ko.applyBindings(subViewModel, document.getElementById('sub'));

    </script>
</body>
</html>

I would greatly appreciate your expert guidance on this issue. Thank you!

Answer №1

Is it better to apply binding separately for each view modal?
Or can we simply create both properties in the same viewModel?

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

Get only the text content from a hyperlink using Tinymce-4

Within tinymce.activeEditor, I currently have this line of innerHTML code (part of a ul-list): <li><a href="#">Important words</a></li> When I place the caret within the sentence "Important words," and click a button with the foll ...

What could be the reason for the malfunction of jQuery's show() function?

Using jQuery, I have implemented a functionality to hide a div using the hide() method. However, upon clicking a link, the div is supposed to show but unexpectedly disappears after appearing briefly. HTML Code Snippet <div id="introContent"> & ...

Encountering a Typescript error while attempting to utilize mongoose functions

An example of a User interface is shown below: import {Document} from "mongoose"; export interface IUser extends Document{ email: string; password: string; strategy: string; userId: string; isValidPassword(password: string): ...

In the Rails environment, it is important to verify that the data sent through $.post method in jQuery is correctly

I’m facing an issue with my jQuery script when trying to post data as shown below: $.post({ $('div#location_select').data('cities-path'), { location_string: $('input#city_name').val() }, }); Although this code work ...

In Vue, the CropperJs image initially appears small, but it returns to its original size after editing

I encountered a peculiar issue while working on a website for image cropping using Vue.js and CropperJs. On the homepage, users can select an image to crop and proceed to the next page where a component named ImageCropper.vue is displayed. Strangely, the c ...

HTML document without a defined delimiter is present

Why is the HTML in a here document not being stored as a string? The HTML content on the screen is displaying along with the "HTMLBLOCK;" code. What could be causing this? <? php <<<HTMLBLOCK <html> <head><title>Menu</titl ...

Leveraging ng-selected in AngularJS to effortlessly select multiple options from a collection

Two arrays of objects are causing me some confusion, with one array being a subset of the other: $scope.taskGroups = [ {id: 1, name: 'group1', description: 'description1'}, {id: 2, name: 'group2', description: 'descr ...

Express.js not redirecting to Angular route, app not starting

I have the following setup in my node.js app.js: app.use('/', routes); app.get('some_api', routes.someApi); app.use(function (req, res) { res.sendFile(path.join(__dirname, 'public', 'index.html')); }); Additio ...

When attempting to open a link in a new tab, the ng-click function fails to execute

In Angular, utilizing both the <code>ng-click and ng-href directives at the same time will result in the click function being executed first. In this scenario, clicking on a link that navigates to Google will be prevented and instead an alert will be ...

Can you explain the distinction between $scope.$root and $rootScope?

When looking at controllers, I noticed that $scope includes $root. Can you explain what $root is and how it differs from the $rootScope that can be injected into the controller? ...

Adjust the color of each list item depending on an array of strings

Within my perspective, I possess a collection of different statuses. <ul> <li>FIRST_STATUS</li> <li>SECOND_STATUS</li> <li>THIRD_STATUS</li> </ul> To continuously update the statuses in my contr ...

Transform gradient backgrounds as the mouse moves

I'm attempting to create a unique gradient effect based on the cursor position. The code below successfully changes the background color of the document body using $(document.body).css('background','rgb('+rgb.join(',')+&a ...

Check the feature that retrieves data from a `json` file

In my util file, I have a function that imports and checks whether a given sectionUUID has a video in the JSON file. import multipleVideos from '../data/videos.json' function hasSectionMultipleVideos (sectionUUID) { return multipleVideos.vide ...

Transfer a term to a different division - JavaScript Object Model

I am trying to achieve a specific task where I need to move one term under another in SharePoint. However, despite my efforts using JSOM and SharePoint 2013, I have not been able to find a direct method for moving terms. The code snippet I have used below ...

Vue - Syntax error: Unexpected token, expecting "}."

I recently started working with Vue and have encountered a simple component issue. Sometimes, when I run npm run serve or save a file that is already being served, I receive the following error message: E:\Development\website\app>npm run ...

Ways to eliminate the worldwide model in SAPUI5

I've been attempting to break down the global model without success. I have a filter button that's set up like this: navToSecond : function (oEvent){ var oObject = this.getView().byId("inp").getValue(); sap.ui.getCore().setModel( ...

What could be causing React to throw an error?

Check out this React Component: GeneralInformation = React.createClass({ totalCaptialRaisedPanel: function() { var offeringInfo = this.props.company.data.offerings.data[0]; var percentageComplete = (offeringInfo.capital_raised / offer ...

retrieving the outcome from a PHP script invoked through Ajax

Having trouble transferring the results of a PHP script to HTML input fields This is my PHP script: $stmt->execute(); if ($stmt->rowCount() > 0){ $row = $stmt->fetch(PDO::FETCH_ASSOC); echo 'Located: ' . $row[&ap ...

Utilize AngularJS's nested ng-repeat to showcase information from two distinct JSON strings simultaneously

I am dealing with two different JSON strings from databases. [{ sport: football, sportid: 1 },{ sport: tennis, sportid: 2 },{ sport: golf, sportid: 3 },{ sport: swimming, sportid: 4 }] and [{ personid: 1, name: ...

Guide to retrieving a string value rather than Json output with a mongodb aggregate function

I have a function that retrieves the value of the 'minHospitalization' field from the database. The response from this function is '[{"minHospitalization":1}]' Instead of returning the value in JSON format, I want to return just ' ...