如何使用knockout js执行AutoComplete [英] How to do AutoComplete using knockout js

查看:80
本文介绍了如何使用knockout js执行AutoComplete的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好



我正在尝试使用淘汰赛js在文本框中自动完成



我用Google搜索并发现了一些很好的链接并试图实现那个。

我试过这个链接



这显示错误

未捕获的SyntaxError:意外的令牌ILLEGAL

我的代码

 <  !DOCTYPE  < span class =code-attribute>   html  >  

< html xmlns = http://www.w3.org/1999/ xhtml >
< head id = head runat = 服务器 >
< title > < span class =code-keyword>< / title >
< script src = http://ajax.googleapis.com/ajax/ libs / jquery / 1.8.2 / jquery.min.js 类型 = text / javascript > ; < / script >
< script src = http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.1.0.js > < span class =code-keyword>< / script >
< / head >
< body >
< 表格 id = form1 runat = server >
< div >
< 输入 数据-bind = jqAuto:{autoFocus:true},jqAutoSource:myPeople,jqAutoQuery:getPeople,jqAutoValue: mySelectedGuid,jqAutoSourceLabel:'displayName',jqAutoS ourceInputValue:'name',jqAutoSourceValue:'guid' / >

< hr / >


< div data-bind = text:mySelectedGuid() ? mySelectedGuid():'未选中' > < / div >

< hr / >

用于测试在其他地方设置模型值:
< 选择 data-bind = 选项:myPeople,optionsCaption:'select a person ...',optionsText:'displayName',optionsValue:'guid',value:mySelectedGuid > < / select >

< hr / >



< / div >
< script >
// jqAuto - 主要绑定(应该包含传递给自动完成的其他选项)
// jqAutoSource - 要填充的数组选择(需要是observableArray)
// jqAutoQuery - 返回的函数选项
// jqAutoValue - 写入所选值的位置
// jqAutoSourceLabel - 应在可能的选择中显示的属性
< span class =code-comment> // jqAutoSourceInputValue - 应在输入框中显示的属性
// jqAutoSourceValue - 用于值的属性
ko.bindingHandlers.jqAuto = {
init: function (element,valueAccessor,allBindingsAccessor,viewModel){
var options = valueAccessor ()|| {},
allBindings = allBindingsAccessor(),
unwrap = ko.utils.unwrapObservable,
modelValue = allBindings.jqAutoValue,
source = allBindings.jqAutoSource,
query = allBindings.jqAutoQuery,
valueProp = allBindings.jqAutoSourceValue,
inputValueProp = allBindings.jqAutoSourceInputValue || valueProp,
labelProp = allBindings.jqAutoSourceLabel || inputValueProp;

// 由select和change事件处理程序共享的函数
function writeValueToModel(valueToWrite){
if (ko.isWriteableObservable(modelValue)) {
modelValue(valueToWrite);
} 其他 { // 写入非-observable
if (allBindings [' _ ko_property_writers']&& allBindings [' _ ko_property_writers'] [< span class =code-string>' jqAutoValue'])
allBindings [' _ ko_property_writers'] [' jqAutoValue'](valueToWrite);
}
}

// 在选择上写下正确的模型的值
options.select = function (event,ui){
writeValueToModel(ui.item?ui.item) .actualValue: null );
};

// 有关更改,请确保它是有效值或清除模型值
options.change = function (event,ui){
var currentValue = $(element).val();
var matchingItem = ko.utils.arrayFirst(unwrap(source), function (item) {
return unwrap(inputValueProp?item [inputValueProp]:item)=== currentValue;
});

if (!matchingItem){
writeValueToModel( null ) ;
}
}

// 保持自动完成当前响应
var currentResponse = null ;

// 处理DO中正在更新的选项,以从源中解除值更新(选项)更新
var mappedSource = ko.dependentObservable({
read: function (){
mapped = ko.utils.arrayMap(unwrap(source), function (item){
var result = {};
result.label = labelProp?unwrap(item [labelProp]):unwrap(item).toString(); // 在弹出选项中显示
result.value = inputValueProp?unwrap(item [inputValueProp]):unwrap( item).toString(); // 在输入框中显示
result.actualValue = valueProp? unwrap(item [valueProp]):item; // 在模型中存储
return 结果;
});
返回映射;
},
写: function (newValue){
source(newValue); // 更新源observableArray,因此我们的映射值(上图)正确
if (currentResponse){
currentResponse(mappedSource());
}
},
disposeWhenNodeIsRemoved:element
});

if (查询){
options.source = function (请求,回复){
currentResponse = response;
query.call( this ,request.term,mappedSource);
}
} 其他 {
// 每当组成源的项目更新时,请确保自动完成知道它
mappedSource.subscribe( function (newValue){
$(element).autocomplete( option source,newValue);
});

options.source = mappedSource();
}


// 初始化自动填充
$(element).autocomplete(options);
},
update: function (element,valueAccessor,allBindingsAccessor,viewModel){
// 基于模型更改的更新值
var allBindings = allBindingsAccessor (),
unwrap = ko.utils.unwrapObservable,
modelValue = unwrap(allBindings.jqAutoValue)|| ' '
valueProp = allBindings.jqAutoSourceValue,
inputValueProp = allBindings.jqAutoSourceInputValue || valueProp;

// 如果我们在输入中写入不同的属性而不是写入如果(valueProp&& inputValueProp!== valueProp){
var source = unwrap(allBindings.jqAutoSource)|| [];
var modelValue = ko.utils.arrayFirst(source, function (item){
return unwrap(item [valueProp])=== modelValue;
})|| {};
}

// 使用应显示的值更新元素输入
$(元素).val(modelValue&& inputValueProp!== valueProp?unwrap(modelValue [inputValueProp]):modelValue.toString());
}
};

function 人(guid,name,email){
this .guid = ko.observable(guid);
this .name = ko.observable(name);
this .email = ko.observable(email);

this .displayName = ko.dependentObservable( function (){
return .name()+ [ + .email()+ ];
},);
}

var viewModel = {
myPeople:ko.observableArray(),
mySelectedGuid:ko .observable( ec361d63-38ae-4ecc-ab46-6c0ef19ed3ac
};


function getPeople(searchTerm,sourceArray){
$ .ajax({
type:< span class =code-string>' POST'
url:' / echo / json /'
data:{
json:' {}'
延迟:。 5
},
成功: function (数据){
// 假响应
var result = [];
for var i = 0 ;我< 5 ; i ++){
result.push( new Person( 5658ff20-f230-4176-97d1-0ac21abfdbd + i,searchTerm + blah + i,searchTerm + blah + i + @ company.com));
}
sourceArray(result);
},
dataType:' json'
});
}


ko.applyBindings(viewModel);
< / script >
< / form >
< / body >
< span class =code-keyword><
/ html >





请帮我解决这个问题



提前致谢

解决方案

(element).val();
var matchingItem = ko.utils.arrayFirst(unwrap(source), function (item) {
return unwrap(inputValueProp?item [inputValueProp]:item)=== currentValue;
});

if (!matchingItem){
writeValueToModel( null ) ;
}
}

// 保持自动完成当前响应
var currentResponse = null ;

// 处理DO中正在更新的选项,以从源中解除值更新(选项)更新
var mappedSource = ko.dependentObservable({
read: function (){
mapped = ko.utils.arrayMap(unwrap(source), function (item){
var result = {};
result.label = labelProp?unwrap(item [labelProp]):unwrap(item).toString(); // 在弹出选项中显示
result.value = inputValueProp?unwrap(item [inputValueProp]):unwrap( item).toString(); // 在输入框中显示
result.actualValue = valueProp? unwrap(item [valueProp]):item; // 在模型中存储
return 结果;
});
返回映射;
},
写: function (newValue){
source(newValue); // 更新源observableArray,因此我们的映射值(上图)正确
if (currentResponse){
currentResponse(mappedSource());
}
},
disposeWhenNodeIsRemoved:element
});

if (查询){
options.source = function (请求,回复){
currentResponse = response;
query.call( this ,request.term,mappedSource);
}
} 其他 {
// 每当组成源的项目更新时,请确保自动完成知道它
mappedSource.subscribe( function (newValue){


(element).autocomplete( option source,newValue);
});

options.source = mappedSource();
}


// 初始化自动填充

(元素).autocomplete(选项);
},
update: function (element,valueAccessor,allBindingsAccessor,viewModel){
// 基于模型更改的更新值
var allBindings = allBindingsAccessor (),
unwrap = ko.utils.unwrapObservable,
modelValue = unwrap(allBindings.jqAutoValue)|| ' '
valueProp = allBindings.jqAutoSourceValue,
inputValueProp = allBindings.jqAutoSourceInputValue || valueProp;

// 如果我们在输入中写入不同的属性而不是写入如果(valueProp&& inputValueProp!== valueProp){
var source = unwrap(allBindings.jqAutoSource)|| [];
var modelValue = ko.utils.arrayFirst(source, function (item){
return unwrap(item [valueProp])=== modelValue;
})|| {};
}

// 使用应显示的值更新元素输入


Hi all

I am trying to do autocomplete in a textbox using knockout js

I Googled this one and found some good link and tried to implement that one.
I tried this Link

This is showing error
Uncaught SyntaxError: Unexpected token ILLEGAL
My Code

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="head" runat="server">
    <title></title><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.1.0.js"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <input data-bind="jqAuto: { autoFocus: true }, jqAutoSource: myPeople, jqAutoQuery: getPeople, jqAutoValue: mySelectedGuid, jqAutoSourceLabel: 'displayName', jqAutoSourceInputValue: 'name', jqAutoSourceValue: 'guid'" />

            <hr />


            <div data-bind="text: mySelectedGuid() ? mySelectedGuid() : 'None selected'"></div>

            <hr />

            For testing setting the model value elsewhere:
            <select data-bind="options: myPeople, optionsCaption: 'select a person...', optionsText: 'displayName', optionsValue: 'guid', value: mySelectedGuid"></select>

            <hr /></div>
        <script>
            //jqAuto -- main binding (should contain additional options to pass to autocomplete)
            //jqAutoSource -- the array to populate with choices (needs to be an observableArray)
            //jqAutoQuery -- function to return choices
            //jqAutoValue -- where to write the selected value
            //jqAutoSourceLabel -- the property that should be displayed in the possible choices
            //jqAutoSourceInputValue -- the property that should be displayed in the input box
            //jqAutoSourceValue -- the property to use for the value
            ko.bindingHandlers.jqAuto = {
                init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
                    var options = valueAccessor() || {},
                        allBindings = allBindingsAccessor(),
                        unwrap = ko.utils.unwrapObservable,
                        modelValue = allBindings.jqAutoValue,
                        source = allBindings.jqAutoSource,
                        query = allBindings.jqAutoQuery,
                        valueProp = allBindings.jqAutoSourceValue,
                        inputValueProp = allBindings.jqAutoSourceInputValue || valueProp,
                        labelProp = allBindings.jqAutoSourceLabel || inputValueProp;

                    //function that is shared by both select and change event handlers
                    function writeValueToModel(valueToWrite) {
                        if (ko.isWriteableObservable(modelValue)) {
                            modelValue(valueToWrite );  
                        } else {  //write to non-observable
                            if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers']['jqAutoValue'])
                                allBindings['_ko_property_writers']['jqAutoValue'](valueToWrite );    
                        }
                    }
        
                    //on a selection write the proper value to the model
                    options.select = function(event, ui) {
                        writeValueToModel(ui.item ? ui.item.actualValue : null);
                    };
            
                    //on a change, make sure that it is a valid value or clear out the model value
                    options.change = function(event, ui) {
                        var currentValue = $(element).val();
                        var matchingItem =  ko.utils.arrayFirst(unwrap(source), function(item) {
                            return unwrap(inputValueProp ? item[inputValueProp] : item) === currentValue;   
                        });
            
                        if (!matchingItem) {
                            writeValueToModel(null);
                        }    
                    }
        
                    //hold the autocomplete current response
                    var currentResponse = null;
            
                    //handle the choices being updated in a DO, to decouple value updates from source (options) updates
                    var mappedSource = ko.dependentObservable({
                        read: function() {
                            mapped = ko.utils.arrayMap(unwrap(source), function(item) {
                                var result = {};
                                result.label = labelProp ? unwrap(item[labelProp]) : unwrap(item).toString();  //show in pop-up choices
                                result.value = inputValueProp ? unwrap(item[inputValueProp]) : unwrap(item).toString();  //show in input box
                                result.actualValue = valueProp ? unwrap(item[valueProp]) : item;  //store in model
                                return result;
                            });
                            return mapped;                
                        },
                        write: function(newValue) {
                            source(newValue);  //update the source observableArray, so our mapped value (above) is correct
                            if (currentResponse) {
                                currentResponse(mappedSource());
                            }
                        },
                        disposeWhenNodeIsRemoved: element
                    });
        
                    if (query) {
                        options.source = function(request, response) {  
                            currentResponse = response;
                            query.call(this, request.term, mappedSource);
                        }
                    } else {
                        //whenever the items that make up the source are updated, make sure that autocomplete knows it
                        mappedSource.subscribe(function(newValue) {
                            $(element).autocomplete("option", "source", newValue); 
                        });
            
                        options.source = mappedSource();
                    }
        
        
                    //initialize autocomplete
                    $(element).autocomplete(options);
                },
                update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
                    //update value based on a model change
                    var allBindings = allBindingsAccessor(),
                        unwrap = ko.utils.unwrapObservable,
                        modelValue = unwrap(allBindings.jqAutoValue) || '', 
                        valueProp = allBindings.jqAutoSourceValue,
                        inputValueProp = allBindings.jqAutoSourceInputValue || valueProp;
        
                    //if we are writing a different property to the input than we are writing to the model, then locate the object
                    if (valueProp && inputValueProp !== valueProp) {
                        var source = unwrap(allBindings.jqAutoSource) || [];
                        var modelValue = ko.utils.arrayFirst(source, function(item) {
                            return unwrap(item[valueProp]) === modelValue;
                        }) || {};             
                    } 

                    //update the element with the value that should be shown in the input
                    $(element).val(modelValue && inputValueProp !== valueProp ? unwrap(modelValue[inputValueProp]) : modelValue.toString());    
                }
            };

            function Person(guid, name, email) {
                this.guid = ko.observable(guid);
                this.name = ko.observable(name);
                this.email = ko.observable(email);
    
                this.displayName = ko.dependentObservable(function() {
                    return this.name() + " [" + this.email() + "]";
                }, this);
            }

            var viewModel = {
                myPeople: ko.observableArray(),
                mySelectedGuid: ko.observable("ec361d63-38ae-4ecc-ab46-6c0ef19ed3ac")
            };


            function getPeople(searchTerm, sourceArray) {
                $.ajax({
                    type: 'POST',
                    url: '/echo/json/',
                    data: {
                        json: '{}',
                        delay: .5
                    },
                    success: function(data) {
                        //fake response
                        var result = [];
                        for (var i = 0; i < 5; i++) {
                            result.push(new Person("5658ff20-f230-4176-97d1-0ac21abfdbd" + i, searchTerm + "blah" + i, searchTerm + "blah" + i + "@company.com"));
                        }
                        sourceArray(result);
                    },
                    dataType: 'json'
                });
            }


            ko.applyBindings(viewModel);​
        </script>
    </form>
</body>
</html>



Please help me to solve this problem

Thanks in advance

解决方案

(element).val(); var matchingItem = ko.utils.arrayFirst(unwrap(source), function(item) { return unwrap(inputValueProp ? item[inputValueProp] : item) === currentValue; }); if (!matchingItem) { writeValueToModel(null); } } //hold the autocomplete current response var currentResponse = null; //handle the choices being updated in a DO, to decouple value updates from source (options) updates var mappedSource = ko.dependentObservable({ read: function() { mapped = ko.utils.arrayMap(unwrap(source), function(item) { var result = {}; result.label = labelProp ? unwrap(item[labelProp]) : unwrap(item).toString(); //show in pop-up choices result.value = inputValueProp ? unwrap(item[inputValueProp]) : unwrap(item).toString(); //show in input box result.actualValue = valueProp ? unwrap(item[valueProp]) : item; //store in model return result; }); return mapped; }, write: function(newValue) { source(newValue); //update the source observableArray, so our mapped value (above) is correct if (currentResponse) { currentResponse(mappedSource()); } }, disposeWhenNodeIsRemoved: element }); if (query) { options.source = function(request, response) { currentResponse = response; query.call(this, request.term, mappedSource); } } else { //whenever the items that make up the source are updated, make sure that autocomplete knows it mappedSource.subscribe(function(newValue) {


(element).autocomplete("option", "source", newValue); }); options.source = mappedSource(); } //initialize autocomplete


(element).autocomplete(options); }, update: function(element, valueAccessor, allBindingsAccessor, viewModel) { //update value based on a model change var allBindings = allBindingsAccessor(), unwrap = ko.utils.unwrapObservable, modelValue = unwrap(allBindings.jqAutoValue) || '', valueProp = allBindings.jqAutoSourceValue, inputValueProp = allBindings.jqAutoSourceInputValue || valueProp; //if we are writing a different property to the input than we are writing to the model, then locate the object if (valueProp && inputValueProp !== valueProp) { var source = unwrap(allBindings.jqAutoSource) || []; var modelValue = ko.utils.arrayFirst(source, function(item) { return unwrap(item[valueProp]) === modelValue; }) || {}; } //update the element with the value that should be shown in the input


这篇关于如何使用knockout js执行AutoComplete的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆