Magento – Knockout JS removes jQuery change event

javascriptjqueryknockoutjsmagento-2.1magento2

I don't know if it is specific to Magento 2 but an already set up HTML node with jQuery change event attached to it will lose its change event when run inside a knockout component with attached VM (view model).

Situation in Magento:

I moved the product options wrapper via a layout xml into a custom block

<referenceBlock name="product.info.form.options">
    // Custom block definition
    <move element="product.info.options.wrapper" destination="custom.block" />
</referenceBlock>

That works without any issues!

Now when wrapping around this moved block a knockout model with Magentos custom "scope" binding, all applied onChange events are getting removed – which means in this case the configurable option select boxes staying disabled.

The change events are getting applied here

$(element).on('change', this, this._configure);

.. which also seems right for me on how to add an event.

So in my template file I do the following to wrap my knockout component (with attached VM) around this html snippet:

<div class="tab-content" data-step="1" data-bind="scope:'times'">
    <?php echo $block->getChildHtml('product_options_wrapper'); ?>
</div>

With change event on product wrapper dropdowns:

enter image description here

Withoout change event on dropdowns when nested inside Knockout component:

enter image description here

Anybody knows if this a thing between KnockoutJS and jQuery or if this has something to do with Magento?

For reference on StackOverflow:

https://stackoverflow.com/questions/45113064/jquery-change-event-removed-when-in-knockout-scope

Best Answer

I'm not sure why the on change event is removed (conflict maybe?), but you can do something similar with Knockout itself:

<select data-bind="event:{ change: yourFunction}">
    <option value="0">0</option>
    <option value="1">1</option>
    <option value="2">2</option>
</select>

Helpful links

This looks better practice to me rather than mixing KO and jQuery.