js 超浓缩 双向绑定

绑定确实是个有趣的话题。

现在我的绑定器有了不少的功能

1. 附着在Object对象上,一切以对象为中心

2. 与页面元素进行双向绑定

3. 与任意对象绑定,主要是应用在绑定到页面元素的一些属性上,比如style,当然也可以绑定到任意用户自定义的对象上

4. 可以绑定到方法,让对象具有AddEventListener类似的功能,这应该是终极的扩展功能了

5. 支持selector,function,object 的参数写法

6. 默认绑定到value或者innerhtml属性上

Object.prototype.bind = function (key, obj, prop, event) {
    var that = this
    if (this[key] == undefined) this[key] = ‘‘;
    var bc = undefined;
    if (!this.__bc__) {
        this.__bc__ = {};
        Object.defineProperty(this, "__bc__", { enumerable: false });
    }
    if (!this.__bc__[key]) {
        this.__bc__[key] = [];
        this.__bc__[key].value = this[key]
        bc = this.__bc__[key];
        Object.defineProperty(this, key, {
            get: function () {
                return bc.value
            },
            set: function (value) {
                if (bc.value == value) return;
                bc.forEach(function (l) { l(value); })
                bc.value = value
            }
        })
    }
    bc = this.__bc__[key];
    if (prop == undefined) prop = "value";
    if (event == undefined) event = ‘change‘;
    if (typeof obj == ‘string‘) {
        var els = document.querySelectorAll(obj);
        function b(el, p) {
            if (el[p] == undefined) p = "innerhtml"
            bc.push(function (value) { el[p] = value; });
            if (el.addEventListener) {
                el.addEventListener(event, function (e) {
                    that[key] = el[p];
                })
            }
            el[p] = bc.value;
        }
        for (var i = 0; i < els.length; i++) {
            var el = els[i];
            b(el, prop)
        }
    } else if (typeof obj == ‘function‘) {
        bc.push(obj);
        obj(bc.value);
    } else if (typeof obj == ‘object‘) {
        var p = prop
        if (obj[p] == undefined) p = "innerHTML"
        bc.push(function (value) { obj[p] = value; })
        obj[p] = bc.value;
        if (obj.addEventListener) {
            obj.addEventListener(event, function (e) {
                that[key] = obj[p];
            })
        }
    } else {
        console.log("obj = " + obj + " 不是 [selector,function,element] 中的任何一种,绑定失败!")
    }
}

广州品牌设计公司https://www.houdianzi.com PPT模板下载大全https://redbox.wode007.com

再来个简单的例子

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>测试项目</title>
    <script src="bind.js"></script>

</head>

<body>
    <h1 class="v1"></h1>
    <input class="v1" type="text" id="i1">
    <input type="text" id="i2">
    <script>
        var a = { value: ‘s‘, s: ‘red‘ }
        a.bind(‘value‘, ".v1", ‘value‘, ‘input‘)
        a.bind(‘s‘, i1.style, ‘background‘)
        a.bind(‘s‘, i2)
    </script>
</body>

</html>
posted @ 2020-12-12 14:27  浅笑·  阅读(95)  评论(0编辑  收藏  举报