【问题标题】:ractive array is changing, but not computed value活性数组正在改变,但不是计算值
【发布时间】:2017-01-12 06:55:32
【问题描述】:

我使用对象数组作为我的 ractive 组件(从 PouchDB 接收)的数据,该组件需要在 ractive 内部过滤以获得正确的输出。但是我尝试过的任何东西——即使被称为“文档”的数据被正确更改,过滤后的又名计算值保持不变。

我尝试了方法:

 new Ractive({
        el: '#container',
        template: Listing,
        magic: true,
        modifyArrays: true,
        data: {docs},
        computed: {
            List: function(){
                let tempList = [];
                for(var i = 0; i < docs.length; i++) {
                    if (docs[i].specificValue == otherValue)  {
                        let newValue = docs[i];
                        tempList.push(newValue);
                    }
                }
                return tempList;
                }
            }
    });

带有辅助对象

Ractive.defaults.data.helper = function () {
        for (var i = 0; i < docs.length; i++) {
            if (docs[i].specificValue == otherValue) {
                return docs[i].whatever ;
            }
        }
    }
 new Ractive({
        el: '#container',
        template: '{{helper()}}',
        magic: true,
        modifyArrays: true,
        data: {List: docs}
    });

Ractive computed property中描述的数据函数

但没有任何事情能按预期进行。当我直接使用文档时,绑定按预期工作。

PS:代码可能看起来有点别扭,因为我只是复制和简化。

【问题讨论】:

  • 你能提供一个简单、可重现的演示吗?

标签: ractivejs


【解决方案1】:

Ractive relies on the presence of this.get() 知道计算依赖于哪些数据。

有了这个, area 属性可以像其他任何属性一样处理。它会响应式更新(因为对 ractive.get() 的调用告诉 Ractive 当宽度或高度发生变化时应该重新计算它),所以你可以这样做......

在您的示例中,您正在直接访问docs。 Ractive 不会意识到 docsList 的依赖项。

下面是使用this.get() 的列表与不使用的列表的比较示例:

var arr = [0, 1, 2, 3];

new Ractive({
  el: 'body',
  template: `
  	<div>Working: {{# workingList }}{{.}}{{/}}</div>
  	<div>Not working: {{# nonWorkingList }}{{.}}{{/}}</div>
  `,
  magic: true,
  modifyArrays: true,
  data: {
    list: arr
  },
  computed: {
    workingList() {
      return this.get('list').map(n => `#${n}`);
    },
    nonWorkingList() {
      return arr.map(n => `#${n}`)
    }
  }
});

setInterval(() => {
  arr.push(arr.length);
}, 1000);
&lt;script src="https://unpkg.com/ractive@0.8.9/ractive.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 谢谢,这让我更清楚了,但我仍然无法正常工作。好像我错过了一些基本点。我设法设置了一个fiddle,其中使用了this.get() - 文档被过滤和呈现,但不是更新。
  • @Torf 更新了fiddle。您不直接访问数组(如doc)。您需要从 Ractive(通过 this.get(stringKeypath))检索它。有关更改,请参见 cmets。
猜你喜欢
  • 2019-05-28
  • 1970-01-01
  • 1970-01-01
  • 2012-11-14
  • 1970-01-01
  • 2014-07-12
  • 1970-01-01
  • 2019-02-07
  • 2019-12-05
相关资源
最近更新 更多