2017-12-10 2 views
0

나는이 주제에 대해 비슷한 질문을 많이하지만, 나는이 문제를 혼자서 해결하려고 노력했기 때문에 나는 그것을 할 수 없었고, 이미 일주일이 지났음을 알고있다.녹아웃과 함께 목록 필터링

내가하려는 것은 텍스트 상자로 목록을 필터링하는 것입니다. 아래 코드 :

HTML :

<!DOCTYPE html> 
<html> 
    <head> 
     <title>Magic Towns</title> 
     <meta charset="UTF-8"> 
     <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
     <meta http-equiv="X-UA-Compatible" content="ie=edge"> 
     <link rel="stylesheet" href="css/styles.css"> 
    <style> 
     html, 
     body { 
     font-family: Arial, sans-serif; 
     height: 100%; 
     margin: 0; 
     padding: 0; 
     } 
     #map { 
     height: 100%; 
     } 
    </style> 
    </head> 
    <body> 

<div id="map"></div> 
<div class="menuContainer"> 
    <span class="center" style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776;</span> 
    <div id="mySidenav" class="sidenav"> 
    <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a> 
    <a href="#"><h1>Locations:</h1></a> 
    <form role="search"> 
        <input type="text" data-bind="value: query, valueUpdate: 'keyup'" placeholder="Search..."> 
    </form> 
    <div data-bind='with currentPlace' > 
     <div data-bind='foreach: placeList'> 
     <p href="#" class="whiteFont" data-bind='text: city, click: closeNav'></p> 
     </div> 
    </div> 
    </div> 
</div> 

    <script src='js/sidebar.js'></script> 
    <script src="js/jquery-3.2.1.min.js"></script> 
    <script src="js/knockout-3.4.2.js"></script> 
    <script src="js/data.js"></script> 
    <script src="js/app3.js"></script> 


    </body> 
</html> 

자바 스크립트 :

var Place = function(data) { 
    this.city = ko.observable(data.city); 
    this.lat = ko.observable(data.lat); 
    this.lng = ko.observable(data.lng); 
}; 


var ViewModel = function() { 
    var self = this; 

    self.placeList = ko.observableArray([]); 
    self.query = ko.observable(''), 

    initialPlaces.forEach(function(placeLocation) { 
     self.placeList.push(new Place(placeLocation)); 
    }); 
    self.currentPlace = ko.observable(this.placeList()[0]); 

}; 



    ko.applyBindings(ViewModel); 

데이터 :

var initialPlaces = [ 
    {"city":"R","lat":22,"lng":-102}, 
    {"city":"T","lat":23,"lng":-110}, 
    {"city":"P","lat":18,"lng":-92}, 
    {"city":"F","lat":25,"lng":-102}, 
]; 

이미이 Link1Link2 다른 사람만을 연결 시도 ... I Javascript와 녹아웃에 멍청한 녀석 (그것에 2 주 이상).

모든 예제를 시도 할 때마다 내 목록이 비어서 아무 것도 표시되지 않습니다.

이 문제를 해결하는 방법에 대한 정보는 어디에서 찾을 수 있습니까? 아니면 모든 의견을 부탁드립니다.

감사합니다.

답변

4

코드에 몇 가지 문제가 있습니다.

  • with 바인딩은 새로운 binding context을 생성합니다. 즉, knockout은 placeList 속성을 개체 안에 넣습니다.이 개체는 with 바인딩 내부에 중첩되어 있습니다.
  • 당신은 당신이 (with currentPlace)
  • 바인딩에 with: 누락 당신은 ko.applyBindings 아닌 함수에 개체를 전달해야합니다. ViewModel과 같은 객체 리터럴을 만들 수 있습니다. 또는 함수를 만든 다음 new 연산자를 사용하여 객체를 만듭니다. 후자를 사용하고 있습니다. (Difference b/n object literal and using new operator on a constructor function)

나는 currentPlace는 당신이 city에 따라 배열을 필터링 할부터 어떻게해야 무엇 확실하지 않다. 당신은 query에 따라 배열을 filter되는이 같은 computed 속성을 만들 수 있습니다

var initialPlaces = [{ 
 
    "city": "London", 
 
    "lat": 22, 
 
    "lng": -102 
 
}, { 
 
    "city": "New York", 
 
    "lat": 23, 
 
    "lng": -110 
 
}, { 
 
    "city": "New Delhi", 
 
    "lat": 18, 
 
    "lng": -92 
 
}]; 
 

 
var Place = function(data) { 
 
    this.city = ko.observable(data.city); 
 
    this.lat = ko.observable(data.lat); 
 
    this.lng = ko.observable(data.lng); 
 
}; 
 

 
var ViewModel = function() { 
 
    var self = this; 
 

 
    self.placeList = ko.observableArray([]); 
 
    self.query = ko.observable(''); 
 

 
    initialPlaces.forEach(function(placeLocation) { 
 
    self.placeList.push(new Place(placeLocation)); 
 
    }); 
 

 
    // everytime query/placeList changes, this gets computed again 
 
    self.filteredPlaces = ko.computed(function() { 
 
    if (!self.query()) { 
 
     return self.placeList(); 
 
    } else { 
 
     return self.placeList() 
 
     .filter(place => place.city().toLowerCase().indexOf(self.query().toLowerCase()) > -1); 
 
    } 
 
    }); 
 
}; 
 

 
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> 
 
<input type="text" data-bind="value: query, valueUpdate: 'keyup'" placeholder="Search..."> 
 

 
<div data-bind="foreach:filteredPlaces"> 
 
    <span data-bind="text:city"></span><br> 
 
</div>

클릭 Run code snippet에 그것을 테스트 할 수 있습니다. Here's a fiddle을 가지고 놀고 싶다면.

+0

adiga 당신은 남자입니다! 당신은 나에게 녹아웃을위한 좋은 튜토리얼을 참조 해 주시겠습니까? –

+0

@AlbertoRocha 비디오 튜토리얼을 모르지만 youtube에서 검색 할 수 있습니다. 녹아웃의 [문서] (http://knockoutjs.com/documentation/introduction.html)은 매우 간단하고 이해하기 쉽습니다. 왼쪽에서 바인딩 목록을 볼 수 있습니다. 하나씩 차례로 살펴볼 수 있습니다. Jsfiddle/Stack Overflow를 검색하여 몇 가지 사항이 명확하지 않은 경우 예제를 검색 할 수도 있습니다. 예를 들어 Google에서 'knockout foreach binding site : jsfiddle.net'을 검색하면 수백 가지의 피들 첩이 발생합니다 (stackoverflow.com으로 사이트를 교체하는 경우와 동일). – adiga

+0

@AlbertoRocha http://www.knockmeout.net/은 간단하고 고급스러운 주제를 다루는 매우 좋은 블로그입니다. [다음은 유용한 바이올린 목록입니다.] (http://www.knockmeout.net/2011/08/all-of-knockoutjscom-live-samples-in.html) 블로그에서 – adiga