【发布时间】:2017-09-14 21:03:00
【问题描述】:
我正在通过 ajax 加载页面,在每个 ajax 请求开始时我都会清理页面,然后在添加的新页面上加载 applybindings。我始终保持一个持久模型,它是更新的视图。
addEventListeners(){
this.subscriptions.push(PubSub.subscribe('route.start', this.removeShopView));
this.subscriptions.push(PubSub.subscribe('route.success', this.addShopView));
}
removeShopView(){
ko.cleanNode(this.currentPage);
}
addShopView(){
this.currentPage = document.querySelector('.page-context');
ko.applyBindings(this.model, this.currentPage);
}
我的问题是,在清理节点时,我似乎正在擦除附加到页面上我的锚链接的事件侦听器。此锚链接包含一个元素,显示我的模型中的产品计数器
<ul>
<li><a class='nav-bag' href="/bag">Bag<span data-bind='text: counter'></span></a></li>
</ul>
我在别处设置的这个事件不再被触发,我的页面刷新而不是运行 ajax 调用。
setupLinks(){
this.pageContextWrap.addEventListener("click", (e) => {
this.linkClickType = undefined;
if (e.target && e.target.nodeName.toLowerCase() == 'a') {
if(href.indexOf(document.domain) === -1) {
console.log("outside link");
this.href = false;
return;
}
// anchor link is local page, ajax load the href
this.doAjaxCall();
e.preventDefault();
e.stopPropagation();
}
});
}
有没有更好的方法来解决这个问题?清理节点是否会删除所有关联的事件侦听器?
【问题讨论】:
-
你不应该使用
cleanNode。您可以将整个应用程序放入 Knockout,将 Ajax HTML 转换为template节点,并在 the template binding 中使用它们。 -
我了解 cleanNode 实际上是由 Knockout 内部使用的,最好模板部分重新渲染代码。关于 Stackoverflow 的 cleanNode 讨论实际上让我误入歧途,直到我找到 stackoverflow.com/questions/15063794/…。在我的例子中,一个 ajax 调用会加载一个新页面,它会替换旧页面。您是否建议我在每次 ajax 调用后使用 ko.applyBindings 将未更改的数据模型绑定到新视图,并在页面的每个部分(例如购物篮)进行模板化?
-
您使用
applyBindings适合您需要做的事情。我不确定最干净/最淘汰赛的做法是什么,但我正在考虑。