我试图了解击倒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>"
});
但是当绑定时,我得到以下错误:
无法处理绑定&#34;点击:function(){return $ root.selectCustomer}&#34;消息:无法读取属性&#39; selectCustomer&#39; 未定义的
我想做的下一件事是将selectedCustomerId
传达给另一个组件。这是否可以使用PubSub同步,这是如何实现的。有人可以给我一个提示从哪里开始。
答案 0 :(得分: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
传递给另一个组件 - 您可以在根视图模型中创建observable(传递给ko.applyBindings
),然后将其传递给您的组件,如下所示:
<customers params='SelectedCustomer:selectedCustomer'></customers>
然后在数据绑定时使用此observable。 请查看此fiddle以获取工作示例。