1. 程式人生 > 實用技巧 >js 超濃縮 雙向繫結

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>