简体   繁体   English

如何使用javascript将数据绑定到多个元素

[英]How to bind data to multiple elements using javascript

I need to implement one-way data binding in multiple places using a JSON object.我需要使用 JSON 对象在多个地方实现单向数据绑定。 Below is the JSON object getting from the server every 10 sec, with the latest status of a user.下面是每 10 秒从服务器获取的 JSON 对象,以及用户的最新状态。

<html>
<head></head>
<body>
<ul>
  <li>User0: <span class="change_status" unique_id="7150032">Busy</span></li>
  <li>User1: <span class="change_status" unique_id="7150031">Offline</span></li>
  <li>User2: <span class="change_status" unique_id="7150030">Online</span></li>
</ul>
<div class="profile">
  <div class="profileimage">
  U
  </div>
  Status: <span class="change_status" unique_id="7150032">Busy</span>
</div>

<script>
function Binding(b) {
    _this = this
    this.elementBindings = []
    this.value = b.object['unique_id']
    this.valueGetter = function(){
        return _this.value;
    }
    this.valueSetter = function(val){
        _this.value = val
        for (var i = 0; i < _this.elementBindings.length; i++) {
            var binding=_this.elementBindings[i]
            binding.element[binding.attribute] = val
        }
    }
    this.addBinding = function(element, unique_id){
        var binding = {
            element: element,
            unique_id: unique_id
        }

        this.elementBindings.push(binding)
        element['innerText'] = _this.value
        return _this
    }

    Object.defineProperty(b.object, b.property, {
        get: this.valueGetter,
        set: this.valueSetter
    }); 

    b.object[b.property] = this.value;
}

obj =  [
  {
    "unique_id": "7150032",
    "status_name": "Busy"
  },
  {
    "unique_id": "7150031",
    "status_name": "Offline"
  },
  {
    "unique_id": "7150030",
    "status_name": "Online",
  }
]

var changeStatusElements = document.getElementsByClassName("change_status")
var binding = new Binding({
    object: obj
  })
for(var i=0; i< changeStatusElements.length; i++){
    var unique_id = changeStatusElements[i]['unique_id']
  binding.addBinding(changeStatusElements[i], unique_id)
}
</script>
</body>
</html>

These statuses will change based on the new JSON that has new statuses.这些状态将根据具有新状态的新 JSON 更改。 Please assume the JSON (contains a live status of the users) will change every 10 sec.请假设 JSON(包含用户的实时状态)将每 10 秒更改一次。

Please correct my code that would be appreciated.请更正我的代码,我们将不胜感激。

Give your ul element an id attribute, so you can reference it from code.给你的ul元素一个 id 属性,这样你就可以从代码中引用它。 I will assume it is called "container".我假设它被称为“容器”。 Initially it should just be an empty element, like最初它应该只是一个空元素,比如

<ul id="container"></ul>

You should also have a URL where to make the request to.您还应该有一个 URL 来发出请求。 I'll assume you have that in a variable url .我假设你在一个变量url有它。

Then, you can add this code:然后,您可以添加以下代码:

(async function request() {
    let response = await fetch(url);
    let { data } = await response.json();
    document.querySelector("#container").innerHTML = data.map(({ unique_id, status_name }, i) =>
        `<li>User${i}: <span class="change_status" unique_id="${unique_id}">${status_name}</span></li>`).join("\n");
    setTimeout(request, 10000);
})();

I have done this.我已经这样做了。 Please check the following code请检查以下代码

function Binding(b) {
    _this = this
    this.statusArrProxy = b[b.property]
    this.statusGetter = function () {
        return _this.statusArrProxy;
    }
    this.statusSetter = function (arr) {
        _this.statusArrProxy = arr
        arr.forEach(a => {
            var elements = document.querySelectorAll('.change_status[' + b.key + '="' + a[b.key] + '"]')
            elements.forEach(node => node[b.attribute] = a[b.value])
        })
    }
    Object.defineProperty(b, b.property, {
        get: this.statusGetter,
        set: this.statusSetter
    })
    b[b.property] = this.statusArrProxy
}

var statusArray = [{ unique_id: 123, status: 'Busy' }, { unique_id: 1234, status: 'Available' }]
var bindingObj = {
    statusArray: statusArray,
    attribute: 'innerHTML',
    property: 'statusArray',
    key: 'unique_id',
    value: 'status'
}
new Binding(bindingObj)
//replace the entire array bindingObj.statusArray = [{ unique_id: 123, status: 'Offline' }, { unique_id: 1234, status: 'Out Of Office' }]

thank you for all support谢谢大家的支持

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM