从动态元素获取挖空视图的大小

Getting size of knockout views from dynamic elements

本文关键字:视图 动态 元素 获取      更新时间:2023-09-26

在我的淘汰赛应用程序中,我有一部分类似于这个结构:

<section class="container">
  <section class="percent-sizes">
     <article class="d3Graph"></article>
  </section> 
  .
  .
  .
  <section class="percent-sizes">
     <article class="d3Graph"></article>
  </section> 
</section>

这些<sections>是动态的,可以动态创建。

本质上,我有一堆<sections>它们占据了屏幕的百分比部分,具体取决于有多少,然后在每个图表中我都有 d3 图表,我必须知道其中的像素大小才能绘制它们。

这些部分中的每一个都有自己的 ViewModel,容器有自己的视图模型,并维护其子项的可观察数组。

创建新<section>时,我需要通过挖空知道<sections>的宽度/高度是多少并重新绘制它们。

淘汰

赛的最佳实践是什么? (我宁愿不手动计算百分比,或使用jQuery选择器来查找元素并手动查询其高度。

为什么不将它们全部包含在可观察数组中,而只需将高度设置为计算值,例如 -

function whateverViewModel() {
    var self = this;
    self.height = ko.computed(function () {
        return (1 / sectionContainer.length);
    });
}
var sectionContainer = ko.observableArray();
sectionContainer.push(new whateverViewModel());
<section data-bind="style: { height: height }"></section>