Extjs中双向数据绑定的一个用法

Extjs的双向数据绑定

Sometimes a component's state, e.g. thecheckedstate of a checkbox or the selected record of a grid, is interesting to other components. When a component is assigned areferenceto identify it, that component will publish some of its key properties in the ViewModel.

In this example, we have the "Admin Key" textfield's disabled config bound to the the checked state of the checkbox. This results in the textfield being disabled until the checkbox is checked. This sort of behavior is well suited for dynamic forms like this:

Ext.define('MyApp.view.TestViewModel', {
    extend: 'Ext.app.ViewModel',
    alias: 'viewmodel.test', // connects to viewModel/type below

    data: {
        firstName: 'John',
        lastName: 'Doe'
    },

    formulas: {
        // We'll explain formulas in more detail soon.
        name: function (get) {
            var fn = get('firstName'), ln = get('lastName');
            return (fn && ln) ? (fn + ' ' + ln) : (fn || ln || '');
        }
    }
});

Ext.create('Ext.panel.Panel', {
    title: 'Sign Up Form',

    viewModel: {
        type: 'test'
    },

    items: [{
        xtype: 'checkbox',
        boxLabel: 'Is Admin',
        reference: 'isAdmin'
    },{
        xtype: 'textfield',
        fieldLabel: 'Admin Key',
        bind: {
            disabled: '{!isAdmin.checked}'
        }
    }]
});

这里在ViewModel的data中并未定义一个isAdmin,但是可以通过双向数据绑定给了textfield。这是因为上面文档中说到的:“When a component is assigned a reference to identify it, that component will publish some of its key properties in the ViewModel”,就是如果组件使用了reference属性,就可以将组件自己的一些关键属性注册到ViewModel的data中去。
解决了我的MenuViewModel中为什么可以在formulas中使用menugrid.selection,因为menugrid组件注册了reference:'menugrid'。

官方文档地址:

extjs官方文档

你可能感兴趣的:(extjs)