我试图理解 knockout 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>"
});
但是在绑定(bind)时,出现以下错误:
Unable to process binding "click: function (){return $root.selectCustomer }" Message: Cannot read property 'selectCustomer' of undefined
接下来我想做的是将 selectedCustomerId
传递给另一个组件。使用 PubSub 同步是否可以实现这一点以及如何实现这一点。有人可以给我提示从哪里开始吗?
最佳答案
在绑定(bind)中使用 $parent
而不是 $root
。 $root
通常指传递给 ko.applyBindings
方法的 View 模型。
此外,您的代码中还有另一个错误 - 在 selectCustomer
方法中,您试图访问不存在的全局变量 selectedCustomerId
。您应该在其前面添加 self
前缀,以便能够访问在 View 模型中创建的局部变量。
var self = this;
self.customers = ko.observableArray();
self.selectedCustomerId = params.SelectedCustomer;
self.selectCustomer = function (data) {
self.selectedCustomerId(data.Id);
};
关于将 selectedCustomerId
传递给另一个组件 - 您可以在 Root View 模型中创建 observable(将其传递给 ko.applyBindings
),然后将其传递给您的组件,例如这个:
<customers params='SelectedCustomer:selectedCustomer'></customers>
然后在数据绑定(bind)时使用这个observable。 检查这个fiddle对于工作示例。
关于knockout.js - Knockout 组件中的函数 (knockoutjs 3.2+),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25524216/