How to employ Events in Knockout JS Magento 2 –Magento 2 events

Here are the following steps that will explain you How to use Events in Knockout JS Magento 2? – Magento 2 events:

  1. Insert Magento 2 events observe r into view file
  2. State the function select Row in view-model

In the previous article, I’ve explained you how to produce a data grid in frontend page using knockout js. Here I’ll shows you how to use Magento 2 events in knockout js. I’m using source code in the sample of the previous article. So please read it before practicing the sample in this post.

After insert event click into each rows in the data table, I got the result below:

magento 2 events

Insert Magento 2 events observe r into view file

/app/code/[NameSpace]/[ModuleName]/view/frontend/web/template/grid.html
<table class="data table base list">

    <thead>

        <tr data-bind="foreach: columns">

            <th data-bind="text: headerText"></th>

        </tr>

    </thead>

    <tbody data-bind="foreach: items">

        <tr data-bind="event: {click : $parent.selectRow}, foreach: columns">

            <td><span data-bind="text:  renderer ? renderer.render($parent) : $parent[rowText] "></span></td>

        </tr>

    </tbody>

</table>

You can see I insert the event observer into <tr> element: <tr data-bind=”event: {click: $parent.selectRow}” >

In this situation, the $parent is the view-model after user clicked on each row in this table, the function select Row in grid.js will be called.

States the function select Row in view-model

/app/code/[NameSpace]/[ModuleName]/view/frontend/web/js/view/grid.js
selectRow: function(data, event) {

    alert('You select item: ' + data.name);

}

It is a very easy function to explain the name of the item which user delected on. You can see the two following  factors in this function :

  • Data: an object which is suggested to item object. So I use “data.name” which means the name of the item.
  • Event: the event object

Also see other events such as dblclick, mouseover, modify (for input element), etc.

<tr data-bind="event: {dblclick : $parent.selectRow}" >
 <tr data-bind="event: {mouseover : $parent.selectRow}" >

I hope the following steps help you how to employ Events in Knockout JS Magento 2 in  Magento 2 events.  Find more Magento tutorial  by our Experts.

Last Update: July 17, 2018  

February 16, 2018   274   Nandini R    Java Script    
Total 2 Votes:
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Google+
http://www.webnexs.com/blog/kb/employ-events-knockout-js-magento-2
Twitter
LinkedIn