ExtJS,如何将 ViewModel 绑定到组件配置参数?

时间:2021-05-30 15:07:41

标签: javascript extjs viewmodel

在 ExtJS 6.02 上,我想将 ViewModel 绑定到我的组件配置参数。

我尝试了这里所说的:https://stackoverflow.com/a/27284556 但它不起作用,它没有约束力。

这会打印 Null 而不是 123

Ext.define('MyApp.viewmodel.Test', {
    extend: 'Ext.app.ViewModel',
    alias: 'viewmodel.test',
    data: {
        serverPathData: ''
    }
});

Ext.define('MyApp.view.TestFileField', {
    extend: 'Ext.form.field.Text',
    xtype: 'TestFileField',

    viewModel: {
        type: 'test'
    },
    config: {
        serverPath: null
    },
    publishes: 'serverPath',
    bind: {
        serverPath: '{serverPathData}'
    }
    , initComponent: function() {
        this.getViewModel().set('serverPathData', '123');
        this.getViewModel().notify();
        console.log(this.getServerPath());
        
        this.callParent()
    }
});

Ext.application({
    name: 'MyApp',
    launch: function() {
        var testFileField = Ext.widget({
            xtype: 'TestFileField',
            renderTo: Ext.getBody()
        });
    }
});

在本例中使用 testFileField.getViewModel().notify(); 确实解决了问题,但在我的情况下却没有。

我有一个共享的视图模型。

1 个答案:

答案 0 :(得分:0)

找到了一个解决方案,如果我在 initComponent 上调用 this.initBindable(); 它可以工作:

Ext.define('MyApp.viewmodel.Test', {
    extend: 'Ext.app.ViewModel',
    alias: 'viewmodel.test',
    data: {
        serverPathData: ''
    }
});

Ext.define('MyApp.view.TestFileField', {
    extend: 'Ext.form.field.Text',
    xtype: 'TestFileField',

    viewModel: {
        type: 'test'
    },
    config: {
        serverPath: null
    },
    publishes: 'serverPath',
    bind: {
        serverPath: '{serverPathData}'
    }
    , initComponent: function() {
        this.initBindable();
        this.getViewModel().set('serverPathData', '123');
        this.getViewModel().notify();
        console.log(this.getServerPath());
        console.log(this.getViewModel().data);
        this.callParent();
    }
});

Ext.application({
    name: 'MyApp',
    launch: function() {
        var testFileField = Ext.widget({
            xtype: 'TestFileField',
            renderTo: Ext.getBody()
        });
    }
});

问题在于这个方法是私有的,并且已经在 beforeRenderafterRender 上调用,我不知道是在 initComponent 还是 constructor 上调用它可能会导致一些问题。