magento2 引入第三方javascript plugin: 如何在checkout加入jquery chosen?

云霖
2023-12-01

magento2有两种主要JS插件封装形式,jQuery UI Widget和Knockout。而大多数情况下,外部引入的javascript plugin都应该实现这两种封装,才能在magento2中完整地利用,主要是因为knockout template不能使用widget,即那些.html文件。checkout page用的是knockout,所以如果要在该页面加入jquery plugin,knockout方式必须实现。

假设你已经了解这些:https://segmentfault.com/a/11...

不解释requirejs-config.js部分,假定已引入chosen并命名为“jquery.chosen”,以下是jQuery UI Widget的代码:

define([
    'jquery',
    'jquery/ui',
    'jquery.chosen'
], function ($){
    $.widget('mage.jqchosen', {
        options: {
            disable_search_threshold: 999,
            width: '100%'
        },
        _init: function () {
            var _self = this;
            if(this.tagName == 'SELECT') {
                $(this.element).chosen(this.options);
            }
            $(this.element).find('select').each(function() {
                var _hidden = $(this).is(':hidden');
                $(this).chosen(_self.options);
                if(_hidden) {
                    var _id = $(this).attr('id')+"_chosen";
                    $("#"+_id).hide();
                }
            });
        }
    });

    return $.mage.jqchosen;
});

将可以用以下代码使用chosen

<div data-mage-init='{"jqchosen":{}}'>
    <select>
        <option>...</option>
    </select>
</div>

以下是knockout形式的插件:

define(['jquery','ko','jquery.chosen'], function($, ko) {
    ko.bindingHandlers.chosen = {
        init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
            if(element.tagName == 'SELECT') {
                $(element).chosen({
                    disable_search_threshold: 999,
                    width:'100%'
                });
            }
        }
    };
});

如果select非手动修改了状态,chosen会因为获取不到event所以不会同步更新,只需要执行jQuery('#id').trigger('chosen:updated');

关于ko如何增加plugin可参考:http://knockoutjs.com/documen...

要把plugin应用到ko组件上,就需要在ko组件的主体加载plugin,由于所有ko组件都来源于Magento_Ui/js/core/app,所以我决定重写这个js,让它加载我的plugin(假设在requirejs-config.js命名为“knockout-chosen”)

// app/design/frontend/<vendor>/<theme>/Magento_Ui/web/js/core/app.js
define([
    './renderer/types',
    './renderer/layout',
    '../lib/knockout/bootstrap',
    'knockout-chosen' // 新增的plugin
], function (types, layout) {
    'use strict';

    types.set(data.types);
    layout(data.components, undefined, true, merge);
});
<div data-bind="scope: 'koexample'">
    <select data-bind="{chosen:true}">
        <option>...</option>
    </select>
</div>
 
<script type="text/x-magento-init">
    {
        "*": {
            "Magento_Ui/js/core/app": {
                "components": {
                    "koexample": {
                        "component": "Vendor_Module/js/ko_example"
                    }
                }
            }
        }
    }
</script>
 类似资料: