Reputation: 15663
I'm working on an search screen, where the user can pick several options and get the results. When the user checks a checkbox, an AJAX request is made and the results are shown on the screen. So the search doesn't have a "Search" button, the query starts when an option is picked.
I'm using KnockoutJS for UI and Sammy for the routes. The search options are bind to the observableArray. The problem is I don't know where I can set the location.hash. What I'm using now is the subscribe function. On KnockoutJS tutorials I saw that the click is bind to the function which sets the hash, but here I don't think is needed to create a click function for each checkbox and I also believe is too much.
Here the Fiddle
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>
The model:
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());
Upvotes: 0
Views: 1064
Reputation: 15663
The fix was easy and effective. Instead of using the "subscribe" method I added a ko.computed call, where I set the hash.
This call was decorated with the "throttle" extender so when more related observables change virtually at the same time, the hash will be set only once, so Sammy will intercept only once the route, big save when this involves AJAX requests.
Here the Fiddle
Upvotes: 2