Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typeahead.js not working in Knockout 3 foreach binding

I updated a web app to Bootstrap 3 and Knockout 3 and consequently lost the built in typeahead that was in Bootstrap 2. I added typeahead.js and it works great unless I have a typeahead within a Knockout 'foreach' binding. I included code that works and fails below along with the Javascript code for the typeahead and Bootstrap binding. Any ideas?

<form role="form">
    <div class="row">
        <div class="col-sm-4 form-group">
            <input type="text" class="form-control sectionNames" data-bind="value: name" />
        </div>
    </div>
    <div data-bind="foreach: section">
        <div class="row">
            <div class="col-sm-4 form-group">
                <input type="text" class="form-control sectionNames" data-bind="value: name" />
            </div>
        </div>
    </div>
</form>

Javascript for typeahead.js and Knockout bindings

<script>
    $( document ).ready(function() {
        $('input.sections').typeahead({
            name: 'sectionName',
            local: [
                'ABC',
                'DEF'
            ]
        });

        ko.applyBindings({
            section : [
                { name: "", other: "1234" },
                { name: "", other: "5678" }
            ]
        });
    });
</script>
like image 898
RickM Avatar asked Jan 12 '23 17:01

RickM


2 Answers

Your best bet for something like a widget, especially when you are rendering elements via templating/control-flow, is to use a custom binding to initialize the widget. For example, you could use something like this:

ko.bindingHandlers.typeahead = {
    init: function(element, valueAccessor) {
        var options = ko.unwrap(valueAccessor()) || {},
            $el = $(element),
            triggerChange = function() {
                $el.change();   
            }

        //initialize widget and ensure that change event is triggered when updated
        $el.typeahead(options)
            .on("typeahead:selected", triggerChange)
            .on("typeahead:autocompleted", triggerChange);        

        //if KO removes the element via templating, then destroy the typeahead
        ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
            $el.typeahead("destroy"); 
            $el = null;
        }); 
    }
};

Here is a sample: http://jsfiddle.net/rniemeyer/uuvUR/

like image 124
RP Niemeyer Avatar answered Jan 14 '23 08:01

RP Niemeyer


You should just override events which respond for valueUpdate in KO

<input type="text"
       class="form-control sectionNames"
       data-bind="
           value: name, 
           valueUpdate: 'typeahead:selected typeahead:autocompleted"
/>
like image 35
Sergey Vayser Avatar answered Jan 14 '23 09:01

Sergey Vayser