gpt4 book ai didi

javascript - Knockout JS 将 View 模型绑定(bind)到多个分布式元素 ID

转载 作者:行者123 更新时间:2023-12-02 23:30:16 25 4
gpt4 key购买 nike

这与我的问题类似,但解决方案似乎是创建一个附近的共同父级。就通用性而言,我能做到的唯一方法是绑定(bind)到 document 或类似的东西,但它达不到目的:

Can I applyBindings to more than one DOM element using Knockout?

是否建议像这样将单个 View 模型实例绑定(bind)到多个ID。我尝试了一下,在简单的情况下它可以工作:

ko.applyBindings(newVm, document.getElementById('grapes'));
ko.applyBindings(newVm, document.getElementById('apples'));

我这样做的原因是我想使用内置功能绑定(bind)到单页应用程序上的特定元素,但这些元素没有共同的父元素。

应用绑定(bind)时,是否会创建 View 模型实例的任何副本,从而导致内存占用?

这不是关于单个页面 View 的多个 View 模型,也不是关于同一元素的多个 View 模型。一个示例用例是 serverConnection View 模型,其中连接和断开连接按钮位于工具栏的顶部,而连接状态位于状态栏的底部。

最佳答案

Is it recommended to bind a single view model instance to multiple IDs

不,不建议这样做。但也不一定是错的...

推荐的方法是使用 with 绑定(bind)。例如:

JS

const serverConnection = new ServerConnection();
const app = new App();

ko.applyBindings({ app, serverConnection });

HTML

<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>

关于javascript - Knockout JS 将 View 模型绑定(bind)到多个分布式元素 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56547378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com