Przeglądaj źródła

Merge pull request #304 from ckeditor/t/303

Feature: Implemented `View#removeChildren`, the opposite of `View#addChildren`. Closes #303.
Oskar Wróbel 8 lat temu
rodzic
commit
f08942a4e2

+ 16 - 0
packages/ckeditor5-ui/src/view.js

@@ -274,6 +274,22 @@ export default class View {
 		children.map( c => this._unboundChildren.add( c ) );
 	}
 
+	/**
+	 * The opposite of {@link #addChildren}. Removes a child view from this view instance.
+	 * Once removed, the child is no longer managed by its parent, e.g. it can be safely used elsewhere,
+	 * becoming a child of another parent view.
+	 *
+	 * @see #addChildren
+	 * @param {module:ui/view~View|Iterable.<module:ui/view~View>} children Child views to be removed.
+	 */
+	removeChildren( children ) {
+		if ( !isIterable( children ) ) {
+			children = [ children ];
+		}
+
+		children.map( c => this._unboundChildren.remove( c ) );
+	}
+
 	/**
 	 * Initializes the view and child views located in {@link #_viewCollections}.
 	 */

+ 33 - 0
packages/ckeditor5-ui/tests/view.js

@@ -105,6 +105,39 @@ describe( 'View', () => {
 		} );
 	} );
 
+	describe( 'removeChildren()', () => {
+		beforeEach( () => {
+			setTestViewClass();
+			setTestViewInstance();
+		} );
+
+		it( 'should remove a single view from #_unboundChildren', () => {
+			const child1 = {};
+			const child2 = {};
+
+			view.addChildren( child1 );
+			view.addChildren( child2 );
+			expect( view._unboundChildren ).to.have.length( 2 );
+
+			view.removeChildren( child2 );
+			expect( view._unboundChildren ).to.have.length( 1 );
+			expect( view._unboundChildren.get( 0 ) ).to.equal( child1 );
+		} );
+
+		it( 'should support iterables', () => {
+			const child1 = {};
+			const child2 = {};
+			const child3 = {};
+
+			view.addChildren( [ child1, child2, child3 ] );
+			expect( view._unboundChildren ).to.have.length( 3 );
+
+			view.removeChildren( [ child2, child3 ] );
+			expect( view._unboundChildren ).to.have.length( 1 );
+			expect( view._unboundChildren.get( 0 ) ).to.equal( child1 );
+		} );
+	} );
+
 	describe( 'init()', () => {
 		beforeEach( createViewWithChildren );