I am trying to display product collection using knockout js binding. But not working. Please guide me.
Also in Magento2 is require to manually applyBinding
when using component
.?
Also please anyone know how to pass data from phtml to js file and bind it with function. Its very difficult structure to implement knockout in Magento2. Can't understand what should we do for even simple render using table with template file.
Here is the code I have implemented.
List PHTML Code.
<?php $_productCollection = $block->getLoadedProductCollection(); ?>
<?php
$jsonData = array(array('Name'=>'chandu','Aje'=>25));
?>
<script type="text/x-magento-init">
{
"*": {
"Magento_Ui/js/core/app": {
"components": {
"example-scope": {
"component": "Kite_Boxes/js/productrender",
"items": <?php echo json_encode($jsonData); ?>
}
}
}
}
}
</script>
<div data-bind="scope: 'example-scope'">
<!-- ko template: getTemplate() --><!-- /ko -->
</div>
Js File is:
define(['ko', 'uiComponent'], function(ko, Component) {
'use strict';
return Component.extend({
defaults: {
items: 'hello',
template: 'Kite_Boxes/productrender'
},
initialize: function() {
this._super();
this.items = ko.observableArray();
this.setProductData();
console.log(this.items);
},
setProductData: function() {
var VM = function () {
this.columnNames = ko.computed(function () {
if (this.items().length === 0)
return [];
var props = [];
var obj = this.items()[0];
for (var name in obj)
props.push(name);
return props;
});
};
var vm = new VM();
//ko.applyBindings(vm);
}
});
});
HTML Template is:
<table>
<thead>
<tr data-bind="foreach: columnNames">
<th><span data-bind="text: $data"></span></th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr data-bind="foreach: $parent.columnNames">
<td data-bind="text: $parent[$data]"></td>
</tr>
</tbody>
</table>
ERROR is::
Uncaught TypeError: Cannot read property 'items' of undefined