You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ExtJS Classic数组深度绑定异常:添加元素后公式未重计算

ExtJS ViewModel公式未响应数组push更新

问题复现代码

Ext.application({
    name: 'Fiddle',

    launch: function () {
        Ext.define('MyViewModel', {
            extend: 'Ext.app.ViewModel',
            alias: 'viewmodel.myviewmodel',

            data: {
                items: ['Item 1', 'Item 2', 'Item 3']
            },
            stores: {
                store: {
                    fields: ['item'],
                    data: []
                }
            },
            formulas: {
                itemCount: {
                    bind: {
                        bindTo: '{items}',
                        deep: true
                    },
                    get: function (data) {
                        //console.log(data);
                        return data.length;
                    }
                },

            }
        });

        Ext.create('Ext.panel.Panel', {
            viewModel: {
                type: 'myviewmodel'
            },

            items: [{
                xtype: 'displayfield',
                fieldLabel: 'Item Count',
                bind: '{itemCount}'
                //bind: '{store.count}'
            }, {
                xtype: 'button',
                text: 'Add item',
                style: 'margin-right: 10px;',
                handler: function () {
                    //console.log('Button 1 clicked');
                    //debugger;
                    let vm = this.up('panel').getViewModel();
                    let stack = vm.get('items');
                    //debugger;
                    stack.push('Item 4');
                    console.log(stack);

                    let store = vm.getStore('store');
                    store.add({
                        item: 'Item'
                    });
                    console.log(store.data.items);
                }
            }],

            renderTo: Ext.getBody()
        });

    }
});

问题说明

上述代码中,ViewModel的公式itemCount通过深度绑定关联到items数组,用于返回数组长度。但点击「Add item」按钮,用push方法向数组添加元素后,itemCount公式并未重新计算更新显示。

我想了解这一限制的原因,目前找到的临时解决方案是使用Ext.data.Store,绑定其count属性就能正常触发更新——只需注释掉bind: '{itemCount}'并启用下方的bind: '{store.count}'即可测试。

Vue对比示例

<script setup>
import { ref } from 'vue'

const msg = ref('Hello World!')
const array = ref(['item 1', 'item 2', 'item 3'])
</script>

<template>
  <h1>{{ msg }}</h1>
  <input v-model="msg">
  <br/>
  <button @click="array.push('Item 4')">
    Click me
  </button>
  <span> Array: {{array}}, length: {{array.length}}</span>
</template>

在Vue的示例中,向数组添加元素后,数组长度的绑定会正常更新。

内容的提问来源于stack exchange,提问作者boggy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 05:37:02