我正在搜索屏幕上,用户可以在其中选择几个选项并获得结果。当用户选中一个复选框时,会发出一个 AJAX 请求并将结果显示在屏幕上。So the search doesn't have a "Search" button, the query starts when an option is picked.
我将 KnockoutJS 用于 UI,将 Sammy 用于路线。搜索选项绑定到 observableArray。问题是我不知道在哪里可以设置 location.hash。我现在使用的是订阅功能。在 KnockoutJS 教程中,我看到单击绑定到设置哈希的函数,但在这里我认为不需要为每个复选框创建单击函数,我也认为太多了。
这里的小提琴
HTML:
<input type="checkbox" value="1" data-bind="checked:sizeOptions" /> Size 1
<br />
<input type="checkbox" value="2" data-bind="checked:sizeOptions" /> Size 2
<br />
<br />
<div data-bind="text: ko.toJSON($root.sizeOptions)"></div>
Calls: <div data-bind="text: $root.calls"></div>
该模型:
function SearchModel() {
var self = this;
self.calls= ko.observable(0);
self.sizeOptions = ko.observableArray([]);
// Should this be a Behaviour? (like click: goToFolder). This would be called on the Sammy rout also
self.sizeOptions.subscribe(function () {
var _calls = self.calls();
_calls = _calls + 1;
self.calls(_calls);
location.hash = "o=" + self.sizeOptions().join();
console.log("subscribe");
});
Sammy(function() {
this.get('#o=:o', function() {
self.sizeOptions(this.params.o.split(','));
console.log("Sammy get");
// do an AJAX request and place the results in an observableArray
});
}).run();
}
ko.applyBindings(new SearchModel());