我有两个组件:面板和自定义文本字段。
该面板有一个 View 模型,我想将该 View 模型中的一个值(称为 testData
)绑定(bind)到自定义文本字段的一个属性(称为 test
)。
这很好用……基本上。
但是,当文本字段的 test
属性更改时,面板 View 模型中的 testData
不会相应更新。我的意思是,当修改子元素(文本字段)的 test
属性时,面板 View 模型的 testData
属性应包含与 test 相同的值
,就像正常的双向绑定(bind)一样。
我不确定我做错了什么,但这是我到目前为止所做的尝试: https://fiddle.sencha.com/#fiddle/20pu&view/editor
Ext.define('MyMain', {
extend: 'Ext.panel.Panel',
alias: 'widget.main',
width: '100%',
bodyPadding: 10,
viewModel: {
data: {
testData: 'Example Data'
}
},
bind: {
title: '{testData}'
},
items: {
xtype: 'myField',
bind: {
test: '{testData}'
}
}
})
Ext.define('MyField', {
extend: 'Ext.form.field.Text',
alias: 'widget.myField',
fieldLabel: 'Data',
width: '100%',
config: {
test: null // when test is changed, it should also affect the {testData} bind of the main component, causing the title to change
},
setTest(value) {
this.test = value + ' modified!' // because of the bind, this /should/ automatically get appied to the viewmodel's `testData` and thus to the panel title
this.setValue(this.test) // whenever the `test` property is changed, we write the contents to the value of the text field (just to visualize the `test` property).
// But as you can see, the panel title will still just say `Example Data` and not `Example Data modified!` as it should.
},
getTest(){
return this.test
}
})
Ext.application({
name : 'Fiddle',
launch : function() {
Ext.create('Ext.container.Viewport', {
items: [{
xtype: 'main'
}]
})
}
})
最佳答案
更新:(阅读您对其他答案的评论后)
通常,在config
block 中提及该属性并将其包含在publishes
中将使任何属性双向绑定(bind)。
ExtJS 会为它生成 getter 和 setter 方法。 setter 方法负责绑定(bind)。现在,每当有人更新属性值(使用 setter)时,新值将传递给绑定(bind)的 viewModel,然后传递给其他组件。
直接访问属性,this.test
或 this.viewModel.data.testData
并为它们赋值不会反射(reflect)在绑定(bind)到该属性的控件中。
如果您为已发布属性的 setter 函数 (setTest
) 提供实现,请确保从中调用 this.callParent(...)
.
使用字段的 value
属性来显示 test
的内容导致了之前的困惑。这是一个 fiddle具有双向可绑定(bind) test
属性,在 MyField
类中没有任何特殊处理。
单击“获取测试”按钮,值应为“示例数据”(来自 viewModel)。
“设置测试数据”按钮将更新 viewModel 中的值。再次使用“获取测试”按钮验证 test
的值是否也已更新。
“设置测试”按钮为字段的 test
属性分配一个新值,这将反射(reflect)在面板的标题中。
看看这个forked fiddle .
在您的实现中,setTest
方法直接将 this.test
的值更改为 value + 'modified!'
。这不会更新 viewModel 中 testData
的值,因为绑定(bind)是通过配置中指定的属性实现的 getter 和 setter 函数工作的。
关于javascript - ExtJs 父子组件双向绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44327622/