Search code examples
javascriptknockout.jssammy.js

Sammy routes based on select element and knockout


<select class="form-control" data-bind="enable: addressBookEntries(), options : addressBookEntries,
               optionsText: 'address',
               value: selectedAddressBook,
               optionsCaption: 'Select address'"></select>

and a Sammy route like :

Sammy(function () {
    this.get('#addressBook/:id', function () {
        ...
    });
});

Is there any way to make that when users changes option on the dropdown it updates the browser location and execute the sammy route ?

I know I can make a computed that do this but I was looking for some way to actually populate the id from an observable. Is it clear?


Solution

  • Essentially, you would need to update the hash route when the observable changes and have Sammy respond to the route.

    Add something like this to your viewmodel:

    selectedAddressBook.subscribe(function(newValue){
       // validate newValue
       // update the hash with the newValue
       window.location.hash = "#addressBook/" + newValue;
    });