【发布时间】:2015-03-29 02:27:12
【问题描述】:
我有一个单页应用程序 (SPA),带有一个主 index.html“shell”页面,并且在这个 shell 中,当用户单击菜单时,它会将其他视图(MVC 部分视图)动态加载到“子“分区。
这些“子视图”本身有自己的视图模型并执行自己的应用绑定。这些动态“子视图”具有可淘汰的可观察数组集合。我希望当用户输入 shell viewmodels 的搜索输入时,过滤当前加载的 ViewModel 的 knockoutobservable 数组。
我在这里找到了可能类似的问题和一篇好文章 - http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html - 但我觉得这个问题是一个不同的转折点,因为每次菜单点击都会动态加载一个新的视图/虚拟机,所以搜索输入需要取消 -绑定,重新绑定。
这里有一些伪代码
Index.html Shell-
<div id="shell">
<ul id="menu" data-bind="foreach: menu">
<li><a data-bind="text:name, attr: { href: href }, click:$root.loadView" /></li>
<li><a data-bind="text:name, attr: { href: href }, click:$root.loadView" /></li>
</ul>
<input id="search" type="search" data-bind="textInput:searchWords" />
<!-- ------------------------------------------ -->
<!-- where sub-content is dynamically loaded to -->
<!-- ------------------------------------------ -->
<div id="sub-view" data-bind="html: subView"></div>
</div>
<script>
function shellViewModel() {
var self = this;
self.menu = ko.observableArray([
{ name: 'ViewA', href: "/path/to/viewA" },
{ name: 'ViewB', href: "/path/to/viewB" }
]);
self.searchWords = ko.observable("");
self.subView = ko.observable("");
self.loadView = function(menu) {
$.ajax({
url: menu.href,
success: (theView) => {
this.subView(theView);
}
});
return false;
}
};
ko.applyBindings(new shellViewModel());
</script>
ViewA.html:
<div id="A">
<ul data-bind="foreach: people">
<li data-bind="text: name"></li>
</ul>
</div>
<script>
function viewModelA() {
var self = this;
self.people = ko.observableArray([
{ name: 'Bert' },
{ name: 'Charles' },
{ name: 'Denise' }
]);
// TIE self.people to shell.searchWords
};
ko.applyBindings(new viewModelA(), document.getElementById("A"));
</script>
【问题讨论】:
标签: knockout.js