2014-08-27 92 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>" 
}); 

但是绑定时,我得到以下错误:

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

我想要做的就是传达selectedCustomerId到另一个组件接下来的事情。这可能使用PubSub同步,这是如何可能的。有人可以给我一个暗示从哪里开始。

+0

你是否在任何地方调用ko.applyBindings?如果是这样,我认为传递给它的模型作为参数被认为是$ root。尝试使用$ parent而不是$ root。 – 2014-08-27 10:28:17

+0

这是3.3版里程碑https://github.com/knockout/knockout/issues/1449 – huocp 2014-08-28 01:55:46

回答

3

在您的绑定中使用$parent而不是$root$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 2014-08-27 12:34:33