这类似于我的问题,但似乎解决方案是创建附近的公共父级。就通用性而言,我唯一可以做到的方法是绑定到document
或类似的东西,但是这样做却违背了目的:
Can I applyBindings to more than one DOM element using Knockout?
建议这样将单个视图模型实例绑定到多个ID。我尝试过,它在简单的情况下也可以工作:
ko.applyBindings(newVm, document.getElementById('grapes'));
ko.applyBindings(newVm, document.getElementById('apples'));
之所以这样做,是因为我想使用内置功能绑定到单个页面应用程序上的特定元素,但是这些元素没有共同的父级。
应用绑定后,是否会创建视图模型实例的任何副本,从而导致该副本成为内存消耗?
这不是关于单个页面视图的多个视图模型,也不是关于同一元素的多个视图模型。一个示例用例就是一个serverConnection
视图模型,其中连接和断开按钮在工具栏的顶部,而连接状态在状态栏的底部。
答案 0 :(得分:1)
建议将单个视图模型实例绑定到多个ID
否,不建议使用。但也不一定错...
推荐的方法是使用with
绑定。例如:
const serverConnection = new ServerConnection();
const app = new App();
ko.applyBindings({ app, serverConnection });
<body>
<header data-bind="with: serverConnection">
<button data-bind="click: connect">Connect</button>
<button data-bind="click: disconnect">Disconnect</button>
</header>
<article data-bind="with: app">
...
</article>
<footer data-bind="with: serverConnection">
<div data-bind="text: statusCode"></div>
</footer>
</body>
const serverConnection = new ServerConnection();
const app = new App(serverConnection);
ko.applyBindings({ app, serverConnection });
function App(connection) {
this.user = connection.user;
this.heading = ko.pureComputed(
() => this.user() ? `Welcome, ${this.user()}` : `Connect to get started...`
);
}
function ServerConnection() {
this.connected = ko.observable(false);
this.connecting = ko.observable(false);
this.user = ko.observable(null);
this.connect = () => {
this.connecting(true);
setTimeout(
() => {
this.connected(true);
this.user("Jane Doe");
this.connecting(false);
},
1500
)
};
this.disconnect = () => {
this.user(null);
this.connected(false);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<header data-bind="with: serverConnection">
<button data-bind="click: connect, disable: connecting">Connect</button>
<button data-bind="click: disconnect, disable: connecting">Disconnect</button>
</header>
<article data-bind="with: app">
<h2 data-bind="text: heading"></h2>
</article>
<footer data-bind="with: serverConnection">
<div data-bind="text: connected() ? '✅' : '?'"></div>
</footer>