Объединение двух функций не работает - PullRequest
0 голосов
/ 29 сентября 2011

Я попытался объединить две функции в коде ниже. Кажется, все работает, за исключением того, что я не могу заставить переменную currentImage.metaData.something работать во второй функции. Я ценю ваш совет.

<script type="text/javascript" src="code.photoswipe-2.1.5.min.js"></script>

<script type="text/javascript">

    (function(window, PhotoSwipe){

        document.addEventListener('DOMContentLoaded', function(){

            var
                options =  {

                    getImageMetaData: function(el){
                        return {
                            href: el.getAttribute('href'),
                            something: el.getAttribute('data-something'),
                            anotherThing: el.getAttribute('data-another-thing')
                        }
                    }

                },
                instance = PhotoSwipe.attach( window.document.querySelectorAll('#Gallery a'), options );


            instance.addEventHandler(PhotoSwipe.EventTypes.onDisplayImage, function(e){

                var currentImage = instance.getCurrentImage();
                console.log(currentImage.metaData.something);
                console.log(currentImage.metaData.anotherThing);

            });


        }, false);


    }(window, window.Code.Util, window.Code.PhotoSwipe));


    (function(window, Util, PhotoSwipe){



        document.addEventListener('DOMContentLoaded', function(){

            var
                sayHiEl,
                sayHiClickHandler = function(e){
                    alert('yo!!!');
                }
                options = {

                    getToolbar: function(){
                        return '<div class="ps-toolbar-close" style="padding-top: 12px;">Close</div><div class="ps-toolbar-play" style="padding-top: 12px;">Play</div><div class="ps-toolbar-previous" style="padding-top: 12px;">Previous</div><div class="ps-toolbar-next" style="padding-top: 12px;">Next</div><div class="say-hi" style="padding-top: 12px;">Say Hi!</div>';
                        // NB. Calling PhotoSwipe.Toolbar.getToolbar() wil return the default toolbar HTML
                    }

                },
                instance = PhotoSwipe.attach( window.document.querySelectorAll('#Gallery a'), options );

                // onShow - store a reference to our "say hi" button
                instance.addEventHandler(PhotoSwipe.EventTypes.onShow, function(e){
                    sayHiEl = window.document.querySelectorAll('.say-hi')[0];
                });

                // onToolbarTap - listen out for when the toolbar is tapped
                instance.addEventHandler(PhotoSwipe.EventTypes.onToolbarTap, function(e){
                    if (e.toolbarAction === PhotoSwipe.Toolbar.ToolbarAction.none){
                        if (e.tapTarget === sayHiEl || Util.DOM.isChildOf(e.tapTarget, sayHiEl)){
                            alert(currentImage.metaData.anotherThing);
                        }
                    }
                });

                // onBeforeHide - clean up
                instance.addEventHandler(PhotoSwipe.EventTypes.onBeforeHide, function(e){
                    sayHiEl = null;
                });


        }, false);


    }(window, window.Code.Util, window.Code.PhotoSwipe));

1 Ответ

2 голосов
/ 29 сентября 2011

Вы объявляете переменную currentImage в первой функции.Переменные, созданные с помощью ключевого слова var, имеют функциональную область, то есть они не видны вне функции (и, следовательно, не видны в вашей второй функции, в данном случае).

Я бы, вероятно, предложил несколькоболее общая реорганизация кода, но простым решением было бы объявить переменную над обеими вашими функциями, сделав ее видимой для обеих.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...