澄清JS中的OOP基础知识并理解对象中的变量范围

时间:2017-03-31 10:38:55

标签: javascript oop knockout.js magento2

我试图了解Magento 2使用knockoutJs和requireJs的方式。这让我想到了一个更广泛的问题,试图理解变量范围如何在对象中起作用? 看看直接从Magento 2中获取的代码:

define([
    'ko',
    'jquery',
    'Magento_Ui/js/lib/knockout/template/loader',
    'mage/template'
], function (ko, $, templateLoader, template) {
    'use strict';

    var blockLoaderTemplatePath = 'ui/block-loader',
        blockContentLoadingClass = '_block-content-loading',
        blockLoader,
        blockLoaderClass,
        loaderImageHref;

    templateLoader.loadTemplate(blockLoaderTemplatePath).done(function (blockLoaderTemplate) {
        blockLoader = template($.trim(blockLoaderTemplate), {
            loaderImageHref: loaderImageHref
        });
        blockLoader = $(blockLoader);
        blockLoaderClass = '.' + blockLoader.attr('class');
    });

    /**
     * Helper function to check if blockContentLoading class should be applied.
     * @param {Object} element
     * @returns {Boolean}
     */
    function isLoadingClassRequired(element) {
        var position = element.css('position');

        if (position === 'absolute' || position === 'fixed') {
            return false;
        }

        return true;
    }

    /**
     * Add loader to block.
     * @param {Object} element
     */
    function addBlockLoader(element) {
        element.find(':focus').blur();
        element.find('input:disabled, select:disabled').addClass('_disabled');
        element.find('input, select').prop('disabled', true);

        if (isLoadingClassRequired(element)) {
            element.addClass(blockContentLoadingClass);
        }
        element.append(blockLoader.clone());
    }

    /**
     * Remove loader from block.
     * @param {Object} element
     */
    function removeBlockLoader(element) {
        if (!element.has(blockLoaderClass).length) {
            return;
        }
        element.find(blockLoaderClass).remove();
        element.find('input:not("._disabled"), select:not("._disabled")').prop('disabled', false);
        element.find('input:disabled, select:disabled').removeClass('_disabled');
        element.removeClass(blockContentLoadingClass);
    }

    return function (loaderHref) {
        loaderImageHref = loaderHref;
        ko.bindingHandlers.blockLoader = {
            /**
             * Process loader for block
             * @param {String} element
             * @param {Boolean} displayBlockLoader
             */
            update: function (element, displayBlockLoader) {
                element = $(element);

                if (ko.unwrap(displayBlockLoader())) {
                    addBlockLoader(element);
                } else {
                    removeBlockLoader(element);
                }
            }
        };
    };
});

如果有人能解释这里的OOP概念以及这些函数如何成为单个类的一部分会很棒。而且,JS中的类和对象的任何指针都会很棒!

0 个答案:

没有答案