javascript - Knockout Js应用绑定(bind)到多个html节点

标签 javascript html knockout.js

我在一个页面上运行了多个 View 模型,为了解决任何潜在的冲突,我将父 html 节点添加到 knockout 应用绑定(bind)文本中。但是,我遇到的一个问题是我不能再使用这些节点之一之外的属性。我试图弄清楚是否有任何方法可以更新我也已绑定(bind)该模型的 View 模型绑定(bind)之外的单个 html 节点。

<html>
<head>
    <script>
        function VM1() {
            this.ViewModelProp1 = ko.observable(1);
            this.NotficationsNumber = ko.observable(1);
        }
        function VM2() {
            this.ViewModelProp2 = ko.observable(1);
        }
        ko.applyBindings(VM1, document.getElementById('vm1'));
        ko.applyBindings(VM1, document.getElementById('vm2'));
    </script>
</head>
<body>
    <!-- I want this property applied to the VM1 -->
    <h1 id="notifiy" data-bind="text: NotficationsNumber"></h1>
    <p id="vm1">
        <strong data-bind="text: ViewModelProp1"></strong>
    </p>
    <p id="vm2">
        <strong data-bind="text: ViewModelProp2"></strong>
    </p>

</body>
</html>

最佳答案

放在自己的容器里就可以了。

<html>
<head>
    <script>
        function VM1() {
            this.ViewModelProp1 = ko.observable(1);
            this.NotficationsNumber = ko.observable(1);
        }
        function VM2() {
            this.ViewModelProp2 = ko.observable(1);
        }
        ko.applyBindings(VM1, document.getElementById('div1'));
        ko.applyBindings(VM1, document.getElementById('vm2'));
    </script>
</head>
<body>
<!-- I want this property applied to the VM1 -->
  <div id='div1'>
     <h1 id="notifiy" data-bind="text: NotficationsNumber"></h1>

    <p id="vm1">
        <strong data-bind="text: ViewModelProp1"></strong>
    </p>
</div>
<p id="vm2">
    <strong data-bind="text: ViewModelProp2"></strong>
</p>

</body>
</html>

关于javascript - Knockout Js应用绑定(bind)到多个html节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34361071/

相关文章:

Javascript 日期对象时区问题 - 不同的时区

javascript - jQuery 函数中的复杂代码

javascript - 无法在html中调用.js(使用knockout)

javascript - 如何在js文件中使用另一个js文件中的函数?

javascript - 带有复选框 'checked' 属性的信息将保存在本地存储中

javascript - 存储可重用的 React+Flux 表单组件(一个组件用于具有不同字段的多个表单)

css - 如何删除 Wordpress 页脚中的背景颜色

html - 使用xpath获取背景图片网址

javascript - 如何在 knockout 绑定(bind)中运行 afterRender 中的函数?

javascript - 从 javascript 文件中 knockout js 模板