Search code examples
javascriptextjsviewmodel

ExtJS, how to bind ViewModel to component config parameters?


On ExtJS 6.02 I would like to bind a ViewModel to my component config parameters.

I tried what it says here: https://stackoverflow.com/a/27284556 but it doesn't work, it's not binding.

This prints Null instead of 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()
        });
    }
});

Using testFileField.getViewModel().notify(); does solve the problem in this example, but in my case it doesn't.

I have a shared viewModel.


Solution

  • Found one solution, if I call this.initBindable(); on initComponent it works:

    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()
            });
        }
    });
    
    

    The problem with this is that this method is private and is already called on beforeRender and afterRender and I don't know if calling it on initComponent or constructor could cause some problem.