【发布时间】:2015-01-04 12:39:36
【问题描述】:
我在处理这种情况的可能性之间迷失了:假设我们有以下限制:
- 淘汰赛
- 带有 Sammy.js 的 SPA - 通过 Ajax 加载的 Html
我的页面:
+-------------------------------+
| #navigation |
+---------+---------------------+
| #sidebar| #content |
| | |
| | |
| | |
+---------+---------------------+
目前,我有一个 appViewModel 来处理我网站的所有 shared 元素的数据绑定:#navigation 和 #sidebar。这个 appViewModel 在我网站的每个页面上都使用了 observable。
appViewModel = function () {
var self = this;
self.sidebarItemArray = ko.observableArray([x, y, z]);
self.currentRoute = ko.observable();
...
self.updateView = function(path, currentRoute) {
return $.get(path, function( data ) {
var $data = $(data);
// Updates #content, TITLE and update the currentRoute observable.
$( '#content' ).replaceWith($data.find('#content'));
document.title = $data.filter('title').text();
self.currentRoute(currentRoute);
}, 'html');
}
Sammy(function() {
this.get(':link'', function() {
self.updateView(this.path, this.params.link);
});
}).run();
}
ko.applyBindings(new appViewModel());
现在,假设#content 是通过Ajax 调用加载的一段DOM。每次用户单击#navigation 或#sidebar 中的链接时,Sammy.js 都会拦截它,然后更新#content。问题是 #content 中的新 DOM 本身具有数据绑定。
1) 首先,我应该在#content 上使用 html 数据绑定、replaceWith(如上)还是使用 template 绑定获取模板的自定义函数? (http://knockoutjs.com/documentation/template-binding.html#note-5-dynamically-choosing-which-template-is-used)? 这里的最佳做法是什么?
2) Sammy 是否应该像文档中或其他地方一样在 appViewModel 中生存就可以了?
3) 一旦 updateView 方法完成,你将如何绑定新的 DOM?像下面这样?是否存在重新绑定某些 DOM 的风险,因为 ko.applyBindings 已经在没有第二个参数的情况下被调用?
ko.applyBindings(new routeSpecificViewModel() , document.getElementById("content"));
感谢您的帮助。
【问题讨论】:
-
这已经有一年多了,我想问一下您是否提出过解决方案?我也面临着同样的困境。
-
老问题 :-) 我最终使用带有 requireJs 和 flatiron/director 作为路由器的 Knockout AMD。这就像一个魅力。使用此堆栈将创建约束,从而避免这些问题。
标签: ajax knockout.js sammy.js