1 Ext.define(‘TestViewModel‘, { 2 extend: ‘Ext.app.ViewModel‘, 3 4 alias: ‘viewmodel.test‘, // connects to viewModel/type below 5 constructor: function(config){ 6 //这里可以看出实例化了几次的 model 7 console.log(config); 8 this.callParent(config); 9 }, 10 11 data: { 12 firstName: ‘John‘, 13 lastName: ‘Doe‘ 14 }, 15 16 formulas: { 17 // We‘ll explain formulas in more detail soon. 18 name: function (get) { 19 var fn = get(‘firstName‘), ln = get(‘lastName‘); 20 return (fn && ln) ? (fn + ‘ ‘ + ln) : (fn || ln || ‘‘); 21 } 22 } 23 }); 24 25 Ext.define(‘TestView‘, { 26 extend: ‘Ext.panel.Panel‘, 27 layout: ‘form‘, 28 29 requires: [ 30 ‘TestViewModel‘ 31 ], 32 33 // Always use this form when defining a view class. This 34 // allows the creator of the component to pass data without 35 // erasing the ViewModel type that we want. 36 viewModel: { 37 type: ‘test‘ // references alias "viewmodel.test" 38 }, 39 40 bind: { 41 title: ‘Hello {name}‘ 42 }, 43 44 defaultType: ‘textfield‘, 45 items: [{ 46 fieldLabel: ‘First Name‘, 47 bind: ‘{firstName}‘ 48 },{ 49 fieldLabel: ‘Last Name‘, 50 bind:{ 51 value: ‘{lastName}‘ 52 } 53 },{ 54 xtype: ‘button‘, 55 text: ‘Submit‘, 56 bind: { 57 hidden: ‘{!name}‘ 58 } 59 },{ 60 xtype: ‘demo‘ 61 }] 62 }); 63 64 Ext.onReady(function () { 65 Ext.create(‘TestView‘, { 66 renderTo: Ext.getBody(), 67 width: 400 68 }); 69 }); 70 71 72 Ext.define(‘Demo‘, { 73 extend: ‘Ext.panel.Panel‘, 74 layout: ‘form‘, 75 alias: ‘widget.demo‘, 76 77 requires: [ 78 ‘TestViewModel‘ 79 ], 80 // Always use this form when defining a view class. This 81 // allows the creator of the component to pass data without 82 // erasing the ViewModel type that we want. 83 initComponent: function(){ 84 //this.ownerCt 85 //var parent = this.findParentByType(‘panel‘); 86 //console.log(parent.title); 87 88 var f = this.getViewModel().get(‘firstName‘); 89 console.log(f); 90 this.callParent(arguments); 91 }, 92 //这个地方为空,就可以和主容器使用相同的一个model,如果你viewModel:{type: test},就相当于又 93 //实例化了一个model 94 viewModel: { 95 96 }, 97 98 bind: { 99 title: ‘{firstName}‘ 100 } 101 102 });
/*
当一个容器中有几个组件公用一个控制器和一个模型
在组件中 使用 controller: ‘main‘时 可以容器组件共用一个,此时实例化容器时,也就是一个控制器
但是在 组件中 使用 viewModel:type: ‘main‘ 时,就需要考虑了,因为每个组件都会实例化一个
模型,如果想容器和组件共用一个模型,一个实例化。就在容器中设置viewModel:{type: ‘main‘},组件中设置 viewModel: {}, 为空就可以了
*/
时间: 2024-10-12 03:00:22