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

发布时间:2019-05-23 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了magento2 引入第三方javascript plugin: 如何在checkout加入jquery chosen?脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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的代码:

@H_126_15@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>

脚本宝典总结

以上是脚本宝典为你收集整理的magento2 引入第三方javascript plugin: 如何在checkout加入jquery chosen?全部内容,希望文章能够帮你解决magento2 引入第三方javascript plugin: 如何在checkout加入jquery chosen?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。