2014-08-27 2 views
2

녹아웃 3.2 구성 요소를 이해하려고하는데 막혔습니다. 녹아웃 구성 요소의 기능 (knockoutjs 3.2+)

나는 구성 요소 "고객"

ko.components.register("customers", { 
    viewModel: function (params) { 
    var self = this; 
    this.customers = ko.observableArray(); 
    this.selectedCustomerId = ko.observable(1); 
    this.selectCustomer = function (data) { 
     selectedCustomerId(data.Id); 
    }; 

    $.getJSON('http://localhost:49435/Customer/GetCustomers', this.customers); 
}, 
template: "<div><table class=\"table table-condensed table-responsive\"><thead><tr><th>Customer ID</th><th>Name</th><th>City</th></tr></thead><tbody data-bind=\"foreach: customers\"><tr><td data-bind=\"text: Id\"></td><td data-bind=\"text: Name, click: $root.selectCustomer\"></td><td data-bind=\"text: City\"></td></tr></tbody></table></div>" 
}); 

그러나이 바인딩 할 때, 나는 다음과 같은 오류를 얻을 : 나는 다른 구성 요소에 selectedCustomerId를 통신하고 싶은

Unable to process binding "click: function(){return $root.selectCustomer }" Message: Cannot read property 'selectCustomer' of undefined

다음 일. 이것은 PubSub 동기화를 사용하여 가능하며 어떻게 가능합니까? 누군가 나에게 시작할 곳을 알려 줄 수 있습니까?

+0

어디서나 ko.applyBindings를 호출합니까? 그렇다면 매개 변수로 전달 된 모델은 $ root로 간주됩니다. $ root 대신 $ parent를 사용하십시오. –

+0

This is ko 3.3 milestone https://github.com/knockout/knockout/issues/1449 – huocp

답변

3

당신의 바인딩에 $root 대신 $parent을 사용하십시오. $root은 일반적으로 ko.applyBindings 메서드에 전달 된 뷰 모델을 참조합니다.

또한 코드에 다른 오류가 있습니다. selectCustomer 메서드에 존재하지 않는 전역 변수 selectedCustomerId에 액세스하려고합니다. 뷰 모델에서 작성된 로컬 변수에 액세스하려면 접두사 인 self을 사용해야합니다.

var self = this; 
    self.customers = ko.observableArray(); 
    self.selectedCustomerId = params.SelectedCustomer; 
    self.selectCustomer = function (data) { 
     self.selectedCustomerId(data.Id); 
    }; 

다른 구성 요소에 selectedCustomerId 전달과 관련하여 - 당신은 당신의 루트 뷰 모델에서 관찰 만드는 (당신이 ko.applyBindings에 전달하는) 다음과 같은 컴포넌트로 전달할 수 있습니다 사용 후

<customers params='SelectedCustomer:selectedCustomer'></customers> 

을 그리고 이것은 데이터 바인딩 때 관찰 할 수 있습니다. 작업 예제는 fiddle을 확인하십시오.

+0

참고 : Yevgeniy의 계획에 따르면,'SelectedCustomerId'를'SelectedCustomer' 매개 변수로 하위 구성 요소에 전달할 수 있습니다. 이 일을하는 방식은 처음에는 나에게 이상한 것처럼 보였습니다. 그러나 당신이 그것에 대해 생각한다면 그것은 외부 세계에 대한 구성 요소의 인터페이스가되었습니다. 각 구성 요소가 어떤 매개 변수를 취해야하는지에 대해 철자를 익히는 것이 좋을 것 같습니다. 또한 Steve Sanderson이 html과 js를 어떻게 분리하는지 살펴보십시오. http://blog.stevensanderson.com/2014/06/11/architecting-large-single-page-applications-with-knockout-js/ – Milimetric

관련 문제