2017-09-19 5 views
0

저장된 '위치'배열에 액세스하는 데 문제가 있습니다. Locations는 객체 리터럴이며 클릭하는 현재 요소에 대한 BASED라는 제목 속성에 액세스하려고합니다. 나는 다음과 같은 코드가 있지만 console.log 제대로 가져올 수 없습니다. 내 추측으로는 'this'와 closure 함수의 사용법이 강하지 않다는 것입니다. 바라건대 내가 누군가에게 약간의 빛을 비추기에 충분할 정도로 이것을 설명했다. 모든 피드백 + 설명은 극명하게 평가됩니다.knockout js를 사용하여 현재 요소를 어떻게 참조합니까?

((!) 참고 : 내 프로젝트 요구 사항은 내가 녹아웃 JS 프레임 워크와 MVVM 형식을 사용할 필요가 있다고)

  1. HTML을

  <ul data-bind="foreach:locationsArray, click:goToLocation"> 
 
      <li><span id="place" data-bind="text:title"></span></li> 
 
      </ul>

2) 자바 스크립트의 ViewModel

var ViewModel = function() { 

    var self = this; 

    self.locationsArray = ko.observableArray(locations); 

    //My goal here is to log the current title of the location selected from the 
    //model. This is the part that is not working.. 
    self.goToLocation = function(self) { 
    console.log(self.locations); 
    } 

3) 자바 스크립트 데이터 모델 (JSON 형식)

var locations = [ 
    { 
    title: 'Nino\'s Pizza', 
    location: { 
     lat: 40.620057, 
     lng: -74.032894 
    } 
    }, 
    { 
    title: 'Shore Road Bike Path', 
    location: { 
     lat: 40.623089, 
     lng: -74.040596 
    } 
    }, 
    { 
    title: 'Paneantico Bakery', 
    location: { 
     lat: 40.619418, 
     lng: -74.0322818 
    }] 

답변

1

당신은 li하지 ul에 클릭 이벤트를 첨부해야합니다. 여기

<ul data-bind="foreach:locationsArray"> 
    <li><span id="place" data-bind="text:title, click:$parent.goToLocation"></span></li> 
</ul> 

, $parentViewModel하지 location 객체에 goToLocation을 찾기 위해 녹아웃을 말할 것이다. 당신의 js에서

다음은 :

var ViewModel = function() { 
    var self = this; 
    self.locationsArray = ko.observableArray(locations); 

    // item will have the data of the clicked li 
    self.goToLocation = function(item) { 
    console.log(item); 
    } 
} 

ko.applyBindings(new ViewModel()); 

여기 adiga 감사 fiddle

+0

입니다! 그 트릭을 .. –