2014-10-07 2 views
2

안녕하세요 내부 (중첩 된) observableArray에서 다음과 같이 항목을 제거하려고하지만 제거 단추가 작동하지 않습니다 (내부 foreach 항목의 경우).중첩 된 observableArray에서 항목 제거

http://jsfiddle.net/aDahT/1871/

HTML :

<h4>People</h4> 
<ul data-bind="foreach: peoples"> 
    <li> 
     Name at position <span data-bind="text: $index"> </span>: 
     <span data-bind="text: name"> </span> 
     <a href="#" data-bind="click: $parent.removePerson">Remove</a> 
     <ul data-bind="foreach:people"> 
      <li> 
       <span data-bind="text: $data"></span> 
       <button data-bind="click: $parent.deletePerson">Remove</button> 
      </li> 
     </ul> 
    </li> 
</ul> 
<button data-bind="click: addPerson">Add</button> 

스크립트 :

var Person = function(name, children){ 
var self = this; 
    self.name = name; 
    self.people = ko.observableArray(children); 
    self.deletePerson = function() { 
     alert(JSON.stringify(self)); 
     self.people.remove(this); 
    } 
} 


function AppViewModel() { 
    var self = this; 

    self.peoples = ko.observableArray([ 
     new Person('Bert', ['baa', 'bbb']), 
     new Person('Charles', ["caa", "cbb"]) 
    ]); 

    self.addPerson = function() { 
     alert(this); 
     self.peoples.push(new Person("New" ,["Daa", "Dbb"])); 
    }.bind(this); 

    self.removePerson = function() { 

     self.peoples.remove(this); 
    } 
} 

ko.applyBindings(new AppViewModel()); 

누군가가 도와 드릴까요? 먼저 감사드립니다.

self.deletePerson = function(viewModel) { 
    self.people.remove(viewModel); 
} 

데모 JSFiddle :

답변

2

그냥 항상 현재 뷰 모델로 설정되어 사용자의 클릭 핸들러의 첫 번째 매개 변수를 사용합니다.

녹아웃은 핸들러의 현재 뷰 모델에 this을 설정하지만 deletePersonremovePerson에는 큰 차이가 있습니다. removePersonthis에서

는 객체 (당신의 Person 개체)입니다하지만 deletePerson에있는이 원시 타입이어야하십시오 문자열.

그러나 넉 아웃은 기능과 상자를 기본 형식을 호출하는 apply를 사용하여 콘솔에 this 로그 아웃 경우이를 확인 JavaScript function call/apply with string

. 그래서 당신은 thisdeletePerson에 박스 문자열을 종료됩니다

String {0: "c", 1: "a", 2: "a", length: 3, [[PrimitiveValue]]: "caa"} 

당신은 그 가치 얻을 valueOf() (또는 toString())를 사용해야합니다 : 당신은 같은 것을 볼 수

self.deletePerson = function() { 
    self.people.remove(this.valueOf()); 
} 

을 그래서 항상 항상 원래 값인 KO에서 제공하는 첫 번째 매개 변수를 사용하십시오.

+0

감사합니다! 이 줄 경고 (JSON.stringify (self))에서 또 다른 질문. 왜 이름 가치를 보여 주지만 사람들을위한 가치를 보여주지 않는가? – peanut

+0

Beacuse'JSON.stringify'는 원시 값만을 보여주고'people'은 관찰 가능한 배열이기 때문에 함수입니다. 'ko.toJSON()'을 사용하여 사람들이 값을 얻을 수 있도록 작성해야합니다.'alert (ko.toJSON (self));' – nemesv

+1

감사합니다. – peanut

0

또한 시도 할 수 있습니다 (jsfiddle) :

<ul data-bind="foreach:people"> 
<li> 
    <span data-bind="text: name"></span> 
    <button data-bind="click: function() {$parent.people.remove($data)}, text: 'remove ' + name"></button> 
</li> 
</ul> 

var model = { 
people: ko.observableArray([{ name: "a"}, { name: "b"}, { name: "c"}]) 
}; 

ko.applyBindings(model); 
관련 문제