AutoComplete Textbox using Durandal JS

2019-09-08 15:04发布

问题:

How can I create an autocomplete textbox using durandal JS. Given code not working.

viewModel(js)

define(['repositories/customerRepository', 'plugins/router', 'plugins/http', 'durandal/app', 'knockout'], function (customerRepository, router, http, app, ko) 
{
return {
    router: router,

    activate: function () {

        var data = customerRepository.listMovies();

        $(function () {
        $("#movie").autocomplete({
            source: data,

            focus: function (event, ui) {
                $("#movie").val(ui.item.name);
                return false;
            },
            select: function (event, ui) {
                $("#movie").val(ui.item.name);
                // $("#friend-id").val(ui.item.id);
                return false;
            }
        })

               .data("ui-autocomplete")._renderItem = function (ul, item) {

                   return $("<li>")
                       .append(
                       "<a>" + "<table><tr><td rowspan=2>" + item.name + "</td></tr><tr><td>" + item.barcode + "</td></tr></table>")
                           .appendTo(ul);

               };
        });

    },




};

});

view(html)

 <input id="movie" type="search" class="form-control" data-bind="value: searchModel.searchTerm" placeholder="Name / Bar code">

回答1:

A good starting point would be to remove your logic from activate and add it to an attached method (assuming you are using Durandal 2.0) If not you would add it to viewAttached. This is fired when the DOM is ready so you woudlnt need to wrap it in a $(function () {});

Give that a try and see if your jquery ui auto complete gets bound correctly.

I personally prefer to use Select2 and then create a ko custom binding for it.

Hope this gets you in the right direction!



回答2:

Durandal is a JavaScript framework intended to handle many things, but it's main purpose is not creating UI elements.

With Durandal you can use Knockout to create declarative two-way data bindings that can provide controls such as an autocomplete text box. Your best bet would be to research how to create AutoComplete text boxes or dropdowns using Knockout.

Google provides many results on the subject

'autocomplete textbox knockout'