@lagudal

Почему некорректно работает popup в М2?

Приветствую, проблема такая.
Хотим сразу же со старта встречать посетителей модальным окном, в котором предлагается выбрать, является ли клиент частным лицом или фирмой. Для того чтобы сразу же показывать соот-е цены.
Т.е. окно всплывает, выбираешь в выпадающем списке опцию одну из двух, жмешь ок и все.
Но вот мои коллеги что то перемудрили по-моему, и я сам не могу найти, где собака зарыта - проблема в том, что после выбора опции в дропдауне окно закрывается, не дожидаясь ок - в общем то пусть бы так и было. Но после закрытия окно через секунду открывается снова, и так пока принудительно не нажмешь ок или х .
И после перезагрузки страницы окно всплывает снова и снова, даже если выбрал первую - дефолтную - опцию и нажал ок. Тут похоже с хранением coockies проблема, если я правильно понимаю.
Сайт в разработке, к сожалению, доступен только из внутренней сети, поэтому могу только привести код попапа.
Собственно, вот он.
spoiler
<div id="custom-popup-modal">
<?php if ($block->getHelper()->usePrivateContent()):?>
	<div class="welcome"><?php echo __("We're happy that you've chosen us!")?></div>
	<div class="choose"><?php echo __("Would you like to continue as a business customer or private customer?")?></div>
	<!--  <li class="switcher-label" data-bind="scope: 'switcher'"><span data-bind="text: switcher().label"></span></li>-->	
	<li class="switcher-dropdown" data-bind="scope: 'switcher'">
		<script type="text/x-magento-init">
 		{
            "*": 
			{
                "Magento_Ui/js/core/app": 
				{
                    "components": 
					{
                        "switcher": 
						{
                            "component": "Anowave_TaxSwitch/js/switcher",
							"config":
							{
								"endpoint": "<?php echo $block->getUrl('taxswitch/index/index') ?>"
							}
                        }
                    }
                }
            }
        }
		</script>
		<script>
			var bindTrack  = <?php echo $block->getHelper()->getTrack() ?>; 
			var bindRender = function()
			{
				return true;
			};
			var bindRenderOptions = function()
			{
				<?php if (false):?>
				
					<?php
					/**
					 * This is kind of dirty workaround. value: switcher().current doesn't seem to work in Magento 2.1.2
					 */
					?>
					var select = jQuery('select[name=tax_display]'), current = jQuery(':hidden[name=current]').val(), current_arg = jQuery(':hidden[name=current_arg]').val();
	
					if (0 < parseInt(current_arg))
					{
						select.val(current_arg);
					}
					else 
					{
						select.val(current);
					}

				<?php endif ?>

				return this;
			};
			var bindChange = function(target, event)
			{
				 if (event.originalEvent)
				 {
				 	if (true == bindTrack.enable)
					{
						/**
						 * Get tax display type
						 */
						bindTrack.fieldsObject['eventLabel'] = jQuery('select[name=tax_display]').find('option:selected:first').text();

						if ('ua' == bindTrack.type) 
						{
							if ('undefined' !== typeof ga)
							{
								ga('send', bindTrack.fieldsObject);						
							}
						}
						else 
						{
							if ('undefined' !== typeof dataLayer)
							{
								bindTrack.fieldsObject['event'] = 'taxSwitch';

								/**
								 * Push event to dataLayer
								 */
								dataLayer.push(bindTrack.fieldsObject);
							}
						}
					}
						
					 jQuery(event.target).parents('form:first').submit();
				 }
			};
	
		</script>
		<div data-bind="text: switcher().select"></div>
		<input type="hidden" id="current" name="current" data-bind="value: switcher().current" />
		<input type="hidden" name="current_arg" value="<?php echo (int) @$_GET['tax_display'] ?>" />
		<form method="post" action="<?php echo $block->getUrl('taxswitch/index/switch')?>">
			<select id="switchoptions" name="tax_display" class="tax_display_select" data-bind="event: { change: bindChange }, afterRender: bindRender, optionsAfterRender: bindRenderOptions, options: switcher().options, optionsText: 'label', optionsValue: 'value', value: switcher().current"></select>
		</form>
	</li>
	<?php else: ?>
	<?php
	/**
	 * This will be deprecated in next version
	 */
	?>
	<li><?php echo __('Show prices') ?></li>
	<li>
		<form method="post" action="<?php echo $block->getUrl('taxswitch/index/switch')?>">
			<input type="hidden" name="form_key" value="<?php echo $block->getFormKey() ?>" />
			<select name="tax_display" class="tax_display_select" onchange="this.form.submit()">
				<?php foreach($block->getOptions() as $option):?>
					<option value="<?php echo $option['value'] ?>" <?php if ($option['checked']):?>selected<?php endif ?>><?php echo $option['label'] ?></option>
				<?php endforeach?>
			</select>
		</form>
	</li>
<?php endif ?>
</div>

<script>
require(
    [
        'jquery',
        'Magento_Ui/js/modal/modal'
    ],
    function(
        $,
        modal
    ) {

    	
        var options = {
            type: 'popup',
            responsive: true,
            innerScroll: true,
            modalClass: 'custom-popup-modal',
            buttons: [{
                text: $.mage.__('Close'),
                class: '',
                click: function () {
                    this.closeModal();
                }
            }]
        };

        $( document ).ready(function() {
    		var popup = modal(options, $('#custom-popup-modal'));
            $('#custom-popup-modal').modal('openModal');
        }); 
    }
);
</script>

В общем буду признателен за помощь, а то тут что то всех заклинило.
  • Вопрос задан
  • 37 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы