2013-04-23 2 views
1

여기는 fiddle입니다.왜 뷰 모델의 속성을 변경 한 후에 applyBindings를 다시 호출해야합니까?

일부 사용자 상호 작용 후에 데이터의 일부를 사용할 수있는 뷰 모델이 있습니다.

applyBindings은 문서 준비가 완료 될 때 이미 호출되었으므로 버튼 클릭 이벤트 중에 다시 호출해야하는 이유는 무엇입니까?

HTML :

<p>first name: 
    <input type="text" data-bind="value: ray.firstName" /> 
</p> 
<p>last name: 
    <input type="text" data-bind="value: ray.lastName" /> 
</p> 
<p>first name: 
    <input type="text" data-bind="value: joe.firstName" /> 
</p> 
<p>last name: 
    <input type="text" data-bind="value: joe.lastName" /> 
</p> 

JS :

function person(firstNm, lastNm) { 
    this.firstName = firstNm; 
    this.lastName = lastNm; 
} 

function myApp() { 
    this.ray = new person(); 
    this.joe = new person(); 
} 

var app = new myApp(); 
app.ray = new person('ray', 'cheng'); 
ko.applyBindings(app); 

$('#showName').on('click', function() { 
    app.joe = new person('joe', 'public'); 
    ko.applyBindings(app); // <-- why is this needed since applyBindings already called above. 
}); 
+0

knockout.js의 [튜토리얼] (http://learn.knockoutjs.com/)을 방문하는 것이 좋습니다. 그들은 매우 도움이됩니다. –

답변

2

당신은 당신이 observables를 사용하지 않기 때문에 두 번 applyBindings를 호출해야합니다. 그리고 Observables Knockout이 없으면 개체가 변경되어 UI를 변경할 수 없다는 것을 추적 할 수 없습니다.

그래서보기 모델은 다음과 같아야합니다

function app() { 
    this.ray = ko.observable(new person()); 
    this.joe = ko.observable(new person()); 
} 

그리고 ko.observable 때문에 반환에게 기능을이처럼 그들을 설정해야합니다

app.ray(new person('ray', 'cheng')); 
app.joe(new person('joe', 'public')); 

을 그리고 data-bind 식의 값을 얻기 위해 값을 얻으려면 ray().firstName과 같은 인수없이 ko.observable으로 전화해야합니다.

<input type="text" data-bind="value: ray().firstName" /> 

데모 JSFiddle.

관련 문제