YUI 自定义组件

 

 

 

源代码

<!DOCTYPE html>
<html>
<head>
<title>3.html</title>

<meta name="keywords" content="keyword1,keyword2,keyword3">
<meta name="description" content="this is my page">
<meta name="content-type" content="text/html; charset=UTF-8">
<script src="http://yui.yahooapis.com/3.17.2/build/yui/yui-min.js"></script>

<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>

<body>


  <style>
    .yui3-js-enabled .yui3-spinner-loading {
        display:none;
    }

    .yui3-spinner-hidden {
        display:none;
    }

    .yui3-spinner {
        display:-moz-inline-stack;
        display:inline-block;
        zoom:1;
        *display:inline;
        vertical-align:middle;
    }

    .yui3-spinner-content {
        padding:1px;
        position:relative;
    }

    .yui3-spinner-value {
        width:2em;
        height:1.5em;
        text-align:right;
        margin-right:22px;
        vertical-align:top;
        border:1px solid #000;
        padding:2px;
    }

    .yui3-spinner-increment, .yui3-spinner-decrement {
        position:absolute;
        height:1em;
        width:22px;
        overflow:hidden;
        text-indent:-10em;
        border:1px solid #999;
        margin:0;
        padding:0px;
    }

    .yui3-spinner-increment {
        top:1px;
        *top:2px;
        right:1px;
        background:#ddd url(../assets/widget/arrows.png) no-repeat 50% 0px;
    }

     .yui3-spinner-decrement {
        bottom:1px;
        *bottom:2px;
        right:1px;
        background:#ddd url(../assets/widget/arrows.png) no-repeat 50% -20px;
     }

    #widget-extend-example {
        padding:5px;
    }

    #widget-extend-example .hint {
        margin-top:10px;
        font-size:85%;
        color:#00a;
    }

</style>


<div id="widget-extend-example">
    A basic spinner widget: <input type="text" id="numberField" class="yui3-spinner-loading" value="20" />
    <p class="hint">Click the buttons, or the arrow up/down and page up/down keys on your keyboard to change the spinner's value</p>
</div>

<script type="text/javascript">
YUI().use("event-key", "widget", function(Y) {

    var Lang = Y.Lang,
        Widget = Y.Widget,
        Node = Y.Node;

    /* Spinner class constructor 首先我们需要定义类*/
    function Spinner(config) {
        Spinner.superclass.constructor.apply(this, arguments);
    }

    /* 然后给类添加名称,名称是静态字段且是规定的格式。名字用于标识组件、事件名前缀
     * Required NAME static field, to identify the Widget class and 
     * used as an event prefix, to generate class names etc. (set to the 
     * class name in camel case). 
     */
    Spinner.NAME = "spinner";

    /*给组件添加属性,自己任意添加,  根据组件的实际需要任意添加属性。属性代表了组件的数据表示和存储
     * The attribute configuration for the Spinner widget. Attributes can be
     * defined with default values, get/set functions and validator functions
     * as with any other class extending Base.
     */
    Spinner.ATTRS = {
        // The minimum value for the spinner.
        min : {
            value:0
        },

        // The maximum value for the spinner.
        max : {
            value:100
        },

        // The current value of the spinner.
        value : {
            value:0,
            validator: function(val) {
                return this._validateValue(val);
            }
        },

        // Amount to increment/decrement the spinner when the buttons or arrow up/down keys are pressed.
        minorStep : {
            value:1
        },

        // Amount to increment/decrement the spinner when the page up/down keys are pressed.
        majorStep : {
            value:10
        },

        // override default ("null"), required for focus()
        tabIndex: {
            value: 0
        },

        // The strings for the spinner UI. This attribute is 
        // defined by the base Widget class but has an empty value. The
        // spinner is simply providing a default value for the attribute.
        strings: {
            value: {
                tooltip: "Press the arrow up/down keys for minor increments, page up/down for major increments.",
                increment: "Increment",
                decrement: "Decrement"
            }
        }
    };

    /* 这个Y.ClassNameManager.getClassName用于生成一个字符,这个字符一般代表了一个class的名字
            如这个例子结果: Spinner.INPUT_CLASS = "yui3-" + Spinner.NAME + value
    Static constant used to identify the classname applied to the spinners value field */
    Spinner.INPUT_CLASS = Y.ClassNameManager.getClassName(Spinner.NAME, "value");

    /* Static constants used to define the markup templates used to create Spinner DOM elements */
    Spinner.INPUT_TEMPLATE = '<input type="text" class="' + Spinner.INPUT_CLASS + '">';
    Spinner.BTN_TEMPLATE = '<button type="button"></button>';

    /* 
     * The HTML_PARSER static constant is used by the Widget base class to populate 
     * the configuration for the spinner instance from markup already on the page.
     *HTML_PARSER这个变量会被base调用,用于处理界面显示配置,
               这个例子的含义:srcNode的值,转化为int返回,srcNode代表了组件的界面dom元素
     * The Spinner class attempts to set the value of the spinner widget if it
     * finds the appropriate input element on the page.
     */
    Spinner.HTML_PARSER = {
        value: function (srcNode) {
            var val = parseInt(srcNode.get("value")); 
            return Y.Lang.isNumber(val) ? val : null;
        }
    };

    /* 这一步很关键了,他将让我们定义的类Spinner变为一个组件,采用继承 Widget的方式
    	函数中的第三个参数是给Spinner这个组件添加自定义方法,相当于这些语句 Spinner.protocol.initializer = function .... 等等
    	这些方法中  initializer、renderUI、 bindUI、syncUI 是必要的,这几个函数关乎组件的生命周期以及渲染。渲染就是组件如何画出来,
       Spinner extends the base Widget class */
    Y.extend(Spinner, Widget, {

        /*
         * initializer is part of the lifecycle introduced by 
         * the Widget class. It is invoked during construction,
         * and can be used to setup instance specific state.
         * 组件初始化
         * The Spinner class does not need to perform anything
         * specific in this method, but it is left in as an example.
         */
        initializer: function() {
            // Not doing anything special during initialization
        },

        /*
         * destructor is part of the lifecycle introduced by 
         * the Widget class. It is invoked during destruction,
         * and can be used to cleanup instance specific state.
         * 销毁
         * The spinner cleans up any node references it's holding
         * onto. The Widget classes destructor will purge the 
         * widget's bounding box of event listeners, so spinner 
         * only needs to clean up listeners it attaches outside of 
         * the bounding box.
         */
        destructor : function() {
            this._documentMouseUpHandle.detach();

            this.inputNode = null;
            this.incrementNode = null;
            this.decrementNode = null;
        },

        /*设置样子 
         * renderUI is part of the lifecycle introduced by the
         * Widget class. Widget's renderer method invokes:
         *
         *     renderUI()
         *     bindUI()
         *     syncUI()
         *
         
         Widget's renderer将会叫用 renderUI() bindUI() syncUI(),这三个函数决定了组件的样子,组件的事件等 呵呵
         
         *
         renderUI is intended to be used by the Widget subclass
         * to create or insert new elements into the DOM. 
         *
         * For spinner the method adds the input (if it's not already 
         * present in the markup), and creates the inc/dec buttons
         */
        renderUI : function() {
            this._renderInput();
            this._renderButtons();
        },

        /* 数据绑定啊及其事件   鼠标事件、以及键盘响应
         * bindUI is intended to be used by the Widget subclass 
         * to bind any event listeners which will drive the Widget UI.
         * 
         * It will generally bind event listeners for attribute change
         * events, to update the state of the rendered UI in response 
         * to attribute value changes, and also attach any DOM events,
         * to activate the UI.
         * 
         * For spinner, the method:
         *
         * - Sets up the attribute change listener for the "value" attribute
         *
         * - Binds key listeners for the arrow/page keys
         * - Binds mouseup/down listeners on the boundingBox, document respectively.
         * - Binds a simple change listener on the input box.
         */
        bindUI : function() {
            this.after("valueChange", this._afterValueChange);

            var boundingBox = this.get("boundingBox");

            // Looking for a key event which will fire continuously across browsers while the key is held down. 38, 40 = arrow up/down, 33, 34 = page up/down
            var keyEventSpec = (!Y.UA.opera) ? "down:" : "press:";
            keyEventSpec += "38, 40, 33, 34";

            Y.on("key", Y.bind(this._onDirectionKey, this), boundingBox, keyEventSpec);
            Y.on("mousedown", Y.bind(this._onMouseDown, this), boundingBox);

            this._documentMouseUpHandle = Y.on("mouseup", Y.bind(this._onDocMouseUp, this), boundingBox.get("ownerDocument"));

            Y.on("change", Y.bind(this._onInputChange, this), this.inputNode);
        },

        /*更新数据显示
         * syncUI is intended to be used by the Widget subclass to
         * update the UI to reflect the current state of the widget.
         * 
         * For spinner, the method sets the value of the input field,
         * to match the current state of the value attribute.
         */
        syncUI : function() {
            this._uiSetValue(this.get("value"));
        },

        /*下面都是被调用的私有方法,不过javascript没有什么私有公有,呵呵
         * Creates the input control for the spinner and adds it to
         * the widget's content box, if not already in the markup.
         */
        _renderInput : function() {
            var contentBox = this.get("contentBox"),
                input = contentBox.one("." + Spinner.INPUT_CLASS),
                strings = this.get("strings");

            if (!input) {
                input = Node.create(Spinner.INPUT_TEMPLATE);
                contentBox.appendChild(input);
            }

            input.set("title", strings.tooltip);
            this.inputNode = input;
        },

        /*
         * Creates the button controls for the spinner and add them to
         * the widget's content box, if not already in the markup.
         */
        _renderButtons : function() {
            var contentBox = this.get("contentBox"),
                strings = this.get("strings");

            var inc = this._createButton(strings.increment, this.getClassName("increment"));
            var dec = this._createButton(strings.decrement, this.getClassName("decrement"));

            this.incrementNode = contentBox.appendChild(inc);
            this.decrementNode = contentBox.appendChild(dec);
        },

        /*
         * Utility method, to create a spinner button
         */
        _createButton : function(text, className) {

            var btn = Y.Node.create(Spinner.BTN_TEMPLATE);
            btn.set("innerHTML", text);
            btn.set("title", text);
            btn.addClass(className);

            return btn;
        },

        /*
         * Bounding box mouse down handler. Will determine if the mouse down
         * is on one of the spinner buttons, and increment/decrement the value
         * accordingly.
         * 
         * The method also sets up a timer, to support the user holding the mouse
         * down on the spinner buttons. The timer is cleared when a mouse up event
         * is detected.
         */
        _onMouseDown : function(e) {
            var node = e.target,
                dir,
                handled = false,
                currVal = this.get("value"),
                minorStep = this.get("minorStep");

            if (node.hasClass(this.getClassName("increment"))) {
                this.set("value", currVal + minorStep);
                dir = 1;
                handled = true;
            } else if (node.hasClass(this.getClassName("decrement"))) {
                this.set("value", currVal - minorStep);
                dir = -1;
                handled = true;
            }

            if (handled) {
                this._setMouseDownTimers(dir, minorStep);
            }
        },

        /*
         * Override the default content box value, since we don't want the srcNode
         * to be the content box for spinner.
         */
        _defaultCB : function() {
            return null;
        },

        /*
         * Document mouse up handler. Clears the timers supporting
         * the "mouse held down" behavior.
         */
        _onDocMouseUp : function(e) {
            this._clearMouseDownTimers();
        },

        /*
         * Bounding box Arrow up/down, Page up/down key listener.
         *
         * Increments/Decrement the spinner value, based on the key pressed.
         */
        _onDirectionKey : function(e) {

            e.preventDefault();

            var currVal = this.get("value"),
                newVal = currVal,
                minorStep = this.get("minorStep"),
                majorStep = this.get("majorStep");

            switch (e.charCode) {
                case 38:
                    newVal += minorStep;
                    break;
                case 40:
                    newVal -= minorStep;
                    break;
                case 33:
                    newVal += majorStep;
                    newVal = Math.min(newVal, this.get("max"));
                    break;
                case 34:
                    newVal -= majorStep;
                    newVal = Math.max(newVal, this.get("min"));
                    break;
            }

            if (newVal !== currVal) {
                this.set("value", newVal);
            }
        },

        /*
         * Simple change handler, to make sure user does not input an invalid value
         */
        _onInputChange : function(e) {
            if (!this._validateValue(this.inputNode.get("value"))) {
                this.syncUI();
            }
        },

        /*
         * Initiates mouse down timers, to increment slider, while mouse button
         * is held down
         */
        _setMouseDownTimers : function(dir, step) {
            this._mouseDownTimer = Y.later(500, this, function() {
                this._mousePressTimer = Y.later(100, this, function() {
                    this.set("value", this.get("value") + (dir * step));
                }, null, true)
            });
        },

        /*
         * Clears timers used to support the "mouse held down" behavior
         */
        _clearMouseDownTimers : function() {
            if (this._mouseDownTimer) {
                this._mouseDownTimer.cancel();
                this._mouseDownTimer = null;
            }
            if (this._mousePressTimer) {
                this._mousePressTimer.cancel();
                this._mousePressTimer = null;
            }
        },

        /*
         * value attribute change listener. Updates the 
         * value in the rendered input box, whenever the 
         * attribute value changes.
         */
        _afterValueChange : function(e) {
            this._uiSetValue(e.newVal);
        },

        /*
         * Updates the value of the input box to reflect 
         * the value passed in
         */
        _uiSetValue : function(val) {
            this.inputNode.set("value", val);
        },

        /*
         * value attribute default validator. Verifies that
         * the value being set lies between the min/max value
         */
        _validateValue: function(val) {
            var min = this.get("min"),
                max = this.get("max");

            return (Lang.isNumber(val) && val >= min && val <= max);
        }
    });

    // Create a new Spinner instance, drawing it's 
    // starting value from an input field already on the 
    // page (the #numberField text box)
    //创建组件,
    var spinner = new Spinner({
        srcNode: "#numberField",
        max:100,
        min:0
    });
    spinner.render();  //weight.render(), renderUI() bindUI() syncUI()
    spinner.focus();   //获得焦点
});
</script>



</body>
</html>


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值