[英]knockoutjs custom elements(components) , viewmodel properties undefined
im stuck a bit with knockoutjs. 我有点被淘汰赛卡住了。
Here is a fiddle for the problem. 这里是一个小提琴的问题。
I've added some simplified logic there. 我在那里添加了一些简化的逻辑。
Shortly, i have a product list, i should populate it from server, and on click on the product item i need the product data(with the observables), so i can update the other view models. 简短地说,我有一个产品列表,我应该从服务器上填充它,然后单击产品项,我需要产品数据(带有可观察对象),以便可以更新其他视图模型。
Note that not all properties are observables (names of products etc, wont change). 请注意,并非所有属性都是可观察到的(产品名称等,不会更改)。 Each product item is a ko component with viewmodel.
每个产品项都是带有viewmodel的ko组件。
Why on button click, the properties of the non-observables , are undefined ? 为什么在单击按钮时, unobservable的属性未定义 ? And also, check the productTemplate , im accessing some properties via product , and the observables via $data (they dont work otherwise - why?).
并且,还要检查productTemplate ,im通过product访问某些属性,以及通过$ data访问可观察对象(否则它们不起作用-为什么?)。 Thanks.
谢谢。
Here is sample html markup 这是示例HTML标记
<div class="products_wrapper">
<section class="products">
<ul data-bind="foreach: { data: products, as: 'product' }">
<li>
<product-item params="product: product"></product-item>
</li>
</ul>
</section>
</div>
Here is the component code: 这是组件代码:
<script type="text/html" id='productTemplate'>
<button type="button" name="product" data-bind="attr: { id: product.ProductId }">
<span data-bind='text: product.Name'></span>
<span class="product-item-quantity" data-bind='text: $data.Quantity'></span>
</button></script>
and here are view models and component registration: 这是视图模型和组件注册:
var some = some || {};
some.viewmodel = some.viewmodel || {};
some.viewmodel.product = function (item) {
var self = this;
//parameters
self.ProductId = item.ProductId;
self.Name = item.Name;
self.Quantity = ko.observable(0);
self.increaseQty = function increaseQty() {
self.Quantity(self.Quantity() + 1);
};
};
some.viewmodel.products = function () {
var self = this;
self.products = ko.observableArray();
self.populate = function (data) {
self.products(data);
};
self.getData = function () {
self.populate(the json data here);
};
};
ko.components.register('product-item', {
viewModel: some.viewmodel.product,
template: {
element: 'productTemplate'
}
});
Init here: 在这里初始化:
var products = new some.viewmodel.products();
ko.applyBindings(products, $('.products_wrapper')[0]);
products.getData();
$(".products").on('click', 'button', function () {
var productcontext = ko.contextFor(this);
var product = ko.dataFor(this);
product.increaseQty();
//$('.debug').append();//debug here
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.