3

I understand Magento 2 registers a number of custom knockout bindings in the Magento_Ui module, specifically through the initialize script in:

vendor/magento/module-ui/view/base/web/js/lib/ko/initialize.js

What's not yet clear to me is how I should go about registering my own custom binding from my own module.

Are there any other examples of custom bindings I could use for reference or any other documentation on the recommended approach to this in Magento 2?

1 Answer 1

0

The answer is Yes.

There's a simple example from the core team shown in module-configurable-product.

//file: vendor/magento/module-configurable-product/view/adminhtml/web/js/variations/steps/attributes_values.js

//connect items with observableArrays
ko.bindingHandlers.sortableList = {
    init: function (element, valueAccessor) {
        var list = valueAccessor();

        $(element).sortable({
            axis: 'y',
            handle: '[data-role="draggable"]',
            tolerance: 'pointer',
            update: function (event, ui) {
                var item = ko.contextFor(ui.item[0]).$data,
                    position = ko.utils.arrayIndexOf(ui.item.parent().children(), ui.item[0]);

                if (ko.contextFor(ui.item[0]).$index() != position) {
                    if (position >= 0) {
                        list.remove(item);
                        list.splice(position, 0, item);
                    }
                    ui.item.remove();
                }
            }
        });
    }
};

Alan Storm also provides a great introduction to this in his KnockoutJS Primer for Magento Developers article.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.