magento2有两种主要JS插件封装形式,widget和knockout。而大多数情况下,外部引入的plugin都应该实现这两种封装,才能在magento2中完整地利用,主要是因为knockout template不能使用widget,即那些.html文件。 假设你已经了解这些:https://segmentfault.com/a/11... 不解释requirejs-config.js部分,假定已引入chosen并命名为“jquery.chosen”,以下是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 = {
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
if(!$(element).data('__chosen_loaded')) {
if(element.tagName == 'SELECT') {
$(element).chosen({
disable_search_threshold: 999,
width:'100%'
});
$(element).data('__chosen_loaded', true);
}
}
}
};
});
只能应用在knockout组件(假设在requirejs-config.js命名为“knockout-chosen”):
// app/code/Vendor/Module/view/frontend/web/js/ko_example.js
define(['ko', 'uiComponent', 'knockout-chosen'], function(ko, Component) {
return Component.extend({});
});
<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>
(责任编辑:最模板) |

免费ecshop便利100带数据微
人气:7852
ecshop团购风格模板
人气:1114
ecshop家具模板|家具商城程
人气:418
Magento主题模板外贸创意模
人气:457
ecshop简黑色模板,合适仿
人气:554
PrestaShop外贸牛奶蛋糕甜点
人气:264