发布于 1年前

CKEditor5 Observable——绑定多个对象或属性

上一节我们学习了如何绑定属性,今天我们继续学习绑定多个属性或者多个Observable对象。

绑定多个属性

如何绑定多个属性,下面我们用代码来说明:

const button = new Button();
const command = editor.commands.get( 'bold' );
button.bind( 'isOn', 'isEnabled' ).to( command, 'value', 'isEnabled' );

其实呢?以上代码就是如下代码的简化版:

button.bind( 'isOn' ).to( command, 'value' );
button.bind( 'isEnabled' ).to( command, 'isEnabled' );

绑定多个Observable对象

绑定可以包含多个Observable对象,在自定义回调函数中组合多个属性。代码如下所示:

const button = new Button();
const command = editor.commands.get( 'bold' );
const editingDocument = editor.editing.view.document;
button.bind( 'isEnabled' ).to( command, 'isEnabled', editingDocument, 'isFocused',
   ( isCommandEnabled, isDocumentFocused ) => isCommandEnabled && isDocumentFocused );

如上所示,button的属性isEnabled被绑定到了command和editingDocument对象的对应属性上,自定义回调函数控制着isEnabled的逻辑值,当command的isEnabled为true并且文档获得焦点的时候,按钮是可用的。

这里有特殊情况是绑定到一个数组Observable。代码如下:

const button = new Button();
const commands =  [ commandA, commandB, commandC ];
button.bind( 'isEnabled' ).toMany( commands, 'isEnabled', ( isAEnabled, isBEnabled, isCEnabled ) => {
   return isAEnabled && isBEnabled && isCEnabled;
} );
//以上可以简写为
button.bind( 'isEnabled' ).toMany( commands, 'isEnabled', ( ...areEnabled ) => {
    return areEnabled.every( isCommandEnabled => isCommandEnabled );
} );

释放绑定

同事件类似,有绑定就有释放绑定,下面说说怎么释放绑定。

释放特定属性绑定

const button = new Button();
const command = editor.commands.get( 'bold' );
button.bind( 'isOn', 'isEnabled' ).to( command, 'value', 'isEnabled' );
// ...
// From now on, button#isEnabled is no longer bound to the command.
button.unbind( 'isEnabled' );

释放全部绑定

const button = new Button();
const command = editor.commands.get( 'bold' );
button.bind( 'isOn', 'isEnabled' ).to( command, 'value', 'isEnabled' );
// ...
// Both #isEnabled and #isOn properties are independent back again.
// They will retain the last values determined by the bindings, though.
button.unbind();

下一节我们介绍Observable的装饰对象方法,decorate(),它提供了一种不改变原始对象的代码却能够增强代码功能的方式。

©2020 edoou.com   京ICP备16001874号-3