2017-11-24 4 views
0

후 목록을 비워 코드는 다음과 같이KnockoutJs 필터 내가 검색 목록을 구축 할 KnockoutJs을 사용하고 검색

HTML : JS 검색 기능의

<input type="search" id="search-bar" placeholder="Enter a name" data-bind="value:query,valueUpdate: 'keyup'"> 
<div id="list" data-bind='template: {foreach: name}'> 
    <li data-bind='text $data'></li> 
</div> 

부 :

this.name = ko.observable(''); 
this.query = ko.observable(''); 
this.search = function (value) { 
    self.name([]); 
    for (var x in name) { 
     if (name[x].toLowerCase().indexOf(value.toLowerCase()) >= 0) { 
      self.name.push(name[x]); 
     } 
    } 
} 

this.query.subscribe(self.search); 

$ .get을 사용하여 다른 URL에서 데이터 (2-D 목록)를 검색 한 다음 구문 분석 한 후 d 구문 분석 된 데이터의 첫 번째 항목 (arsed_data [i] [0])을 코드에 표시된 이름으로 검색합니다.

목록은 검색 상자 항목에 따라 콘텐츠를 필터링하기위한 것이고 처음에는 모든 이름을 표시하지만 검색 상자에 내용을 입력하자마자 이름 목록이 비어있게되며 가능한 원인이 될 수 있습니다. 그것을 고칠 방법이 있습니까?

+0

'자기'란 무엇입니까? 표시하지 않은 코드에'var self = this;'를 설정 했습니까? –

답변

0

계산 도입하는 관찰 (예를 들어 self.filteredNames) 모두 self.names 배열에 의존 할 것이며 self.query 의 현재 값 그런 다음 self.filteredNames 대신 조각의 self.names의에 템플릿 바인딩 할 수 있습니다 (이것은 실제로 ko.observableArray해야한다) 보기 모델의 정의는 다음과 같을 수 있습니다 :

self = this; 
/* ... any other code related to VM */ 
self.names = ko.observableArray([]); // it's supposed to be later filled with AJAX requests 
// self.names = ko.observableArray(['foo', 'bar', 'baz']); // however you can try with this not to bother with actual data loading 
self.query = ko.observable(''); 
self.filteredNames = ko.pureComputed(function(){ 
    // value of this pureComputed observable would be automatically updated each time either self.query or self.names is updated 
    return self.names().filter(function(item) { 
     return item.toLowerCase().indexOf(self.query().toLowerCase()) >= 0; 
    }); 
}); 
/* ... any other code related to VM */ 

는 다음과 같이 볼 수 있었다 어떻게 작동하는지 테스트 할 수있는 마크 업 버전 :

<input type="search" id="search-bar" placeholder="Enter a name" data-bind="value:query,valueUpdate: 'keyup'"> 
<ul id = "list" data-bind='foreach: filteredNames'> 
    <li data-bind=' text: $data'></li> 
</div> 
1

push과 같은 배열 방법을 관찰 가능 항목에 직접 사용하려면 관측 가능 항목이 아닌 observable array으로 지정해야합니다. 예컨대 : 나중에 self.name([])이 비록

하지

this.name = ko.observable(''); 

this.name = ko.observableArray(); 

는 관찰은 아직도 관측 배열 (값이 배열입니다) 단지 관측이다.

(나는 당신이 어딘가에 당신이 보여준 코드 위에 var self = this;이 있으리라 믿고있어.)

을 또한, 이름 의 배열이기 때문에, 당신은 name보다 오히려 names를 호출 할 수 있습니다.


사이드 참고 : for (var x in name) {에서 name가 배열 인 경우, 그건하지 어떻게해야 배열을 통해 루프. 어레이를 루프하는 여러 가지 올바른 방법은 this question's answers을 참조하십시오.


사이드 노트 2 : template 당신의 HTML 바인딩은 용의자를 보인다. 별도의 템플릿이 아닌 HTML을 바로 제공합니다. 그래서 그것은 단지 data-bind="foreach: name"이어야합니다. 내가 제안