Vanilla JS / HTML:将html对象连接到内部数据模型/数组的最佳实践

时间:2019-02-05 17:06:17

标签: javascript html

我有一个缩略图视图,其中包含x个项目,这些项目内部存储在数组中。 最初的请求之后,不再进行服务器通信,因此以后将在浏览器中处理所有事情。

在当前解决方案中,我为每个html缩略图项目提供其内部数据模型中相应索引的ID,这样,在单击缩略图后,我便知道要加载哪些数据。

在我尝试执行删除操作之前,我认为这是一个好主意,因此可以删除任何位置的任何项目,也可以将缩略图项目拖放到周围。

所以在我当前的解决方案中,我将需要在每次更新后遍历每个html缩略图项以调整索引,这不是一个很好的解决方案。

我不相信我会遇到性能问题,因为缩略图包含超过100个项目是非常令人怀疑的,但是我想知道在哪里有更好的解决方案或最佳做法来使它变得更好。

我不能以任何方式或形式来影响数据模型/数组,因此使用uid映射是不可选择的,也不能使用任何框架,因此将需要有效的解决方案。

<button class="thumbNailItem" id="tni#5"><h3>BOLD</h3><p>My Description</p></button>
this.deleteStep = function() {
  let thumbParent = document.getElementById('thumbNailParent');
  this.curTC.testSteps.splice(this.curStep.index, 1);

  thumbParent.removeChild(thumbNailParent.children[this.curStep.index]);

  //would need to implement loop to correct all 'tni#ids'

  if (this.curStep.index <= thumbParent.children.length) {
    thumbParent.children[this.curStep.index].click();
  }

1 个答案:

答案 0 :(得分:1)

解释

考虑到我们对所要查找的完全信息知之甚少,这是一种简单的方式,您可以简单地处理数据,有些事件和一些渲染,仅使用本机JavaScript。

如果您需要一些文档来理解此代码,强烈建议您看一下MDN,我想我想您可以在很大程度上理解它。如前所述,要实现此目的,我仅使用template literals来处理HTML的呈现方式。

您可以使用许多方法来本质上来解决相同的问题,但是在我看来,这种方法对于所发生的事情是干净,清晰和简洁的。

(function () {
  "use strict";
  
  // Just some dummy data for the time being. 
  let data = [
    {name: "Jack", age: 18},
    {name: "Leah", age: 32},
    {name: "Jay", age: 45}
  ];
  
  // Simple reference to the app div.
  const app = document.getElementById("app");
  
  // How you want to handle the click event for each button. 
  const handler = e => {
    data.splice(e.target.id, 1);
    render();
  };
  
  // A simple function to handle dispatching the events. 
  const dispatchEvents = () => {
    document.querySelectorAll(".profile button").forEach(btn => btn.onclick = handler);
  };
  
  // A simple render method. 
  const render = () => {
    app.innerHTML = data.map((o, i) => `<div class="profile">
      <p class="username">Name: ${o.name}</p>
      <p class="userage">Age: ${o.age}</p>
      <button id=${i}>DELETE</button>
    </div>`).join("");
    dispatchEvents();
  };
  
  // Initial render. 
  render();
})();
<div id="app"></div>