CK5还可以将模板的属性绑定到可观测对象属性,如下代码所示:
import {View} from 'ckeditor5/src/ui';
export default class Button extends View {
constructor(){
super();
this.type = 'button';
const bind = this.bindTemplate;
// this.label is observable but undefined.
this.set( 'label' );
// this.isOn is observable and false.
this.set( 'isOn', false );
// this.isEnabled is observable and true.
this.set( 'isEnabled', true );
this.setTemplate( {
tag: 'button',
attributes: {
class: [
// The 'ck-on' and 'ck-off' classes toggle according to the #isOn property.
bind.to( 'isOn', value => value ? 'ck-on' : 'ck-off' ),
// The 'ck-enabled' class appears when the #isEnabled property is false.
bind.if( 'isEnabled', 'ck-disabled', value => !value )
],
type: this.type
},
children: [
{
// The text of the button is bound to the #label property.
text: bind.to( 'label' )
}
]
} );
}
}
这里的button对象有三个可观测属性,使用bind方法将isOn和isEnabled绑定到class属性;同时将label绑定到text属性。
接下来是使用button的代码
const button = new Button();
// Render the button to create its #element.
button.render();
button.label = 'Bold'; // <button class="ck-off" type="button">Bold</button>
button.isOn = true; // <button class="ck-on" type="button">Bold</button>
button.label = 'B'; // <button class="ck-on" type="button">B</button>
button.isOff = false; // <button class="ck-off" type="button">B</button>
button.isEnabled = false; // <button class="ck-off ck-disabled" type="button">B</button>
document.body.appendChild( button.element );
下面我们看看全部执行会产生一个什么样的button:
从以上生成的按钮和代码可以看出当改变button的属性时,对应的class属性值和text的值也发生了变化。
下一节我们学习怎么对绑定的属性进行传播和共享。