1

I am trying to implement custom binding in knockout to create a select element. One difference why I am no using select binding - is because my select will always be the same.

The reason behind using custom binding is because I have a lot of places where the same select will be used and I hope that this will make my code simpler. So my attempt can be found in this fiddle and currently I am struggling with update function (I want to be able to retrieve my selected language).

ko.bindingHandlers.langSelect = {
    init: function(element, valueAccessor){
        var langCur = ko.utils.unwrapObservable(valueAccessor());
        ko.utils.domNodeDisposal.addDisposeCallback(element, function (){
            $(element).remove();
        });

        var list = '', lang = ['en', 'de', 'ja'], i, l = lang.length, s ='';
        for (i = 0; i < l; i++){
            s = (lang[i] === langCur ) ? 'selected' : '';
            list += '<option value="'+ lang[i] +'"'+ s +'>'+ lang[i] +'</option>';
        }

        $(element).html(list);
    },
    update: function(element, valueAccessor){

    }
}

Can anyone help me with this? If custom binding is not the best option, I do not mind changing it.

JotaBe
  • 38,030
  • 8
  • 98
  • 117
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • I don't really understand the point, I must say. If the same `select` is to be shown in different places, why not just put the same markup? With a single source re-used? – GôTô May 26 '14 at 09:11
  • @GôTô the point is to save selected language for every custom observable. – Salvador Dali May 27 '14 at 07:56
  • @robert.westerlund Cool, thank you. Please post this as an answer, so that I would be able to upvote it. – Salvador Dali May 27 '14 at 08:23

1 Answers1

1

A good way to get to what you want is to create a template to bind to. You can read more about templates at the knockout documentation page for the template binding. Here's an example with your languageselector:

The template HTML:

<script type="text/html" id="languageSelectorTemplate">
    <select data-bind="options: ['en','de','ja'], value: selectedLanguage"></select>
</script>

JS:

function AppViewModel() {
    this.lang = ko.observable("de");
}

ko.applyBindings(new AppViewModel());

Example of using the template:

<div data-bind="template: {name: 'languageSelectorTemplate', data: { selectedLanguage: lang } }"></div>

You can find the above example running at http://jsfiddle.net/8a9JB/2/.

Robert Westerlund
  • 4,750
  • 1
  • 20
  • 32