Skip to content

Commit

Permalink
Merge pull request #501 from sveltejs/gh-498-b
Browse files Browse the repository at this point in the history
allow dynamic each-block to have static else-block
  • Loading branch information
Rich-Harris authored Apr 19, 2017
2 parents 1a96dd3 + 872e904 commit 6b2c927
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 10 deletions.
32 changes: 22 additions & 10 deletions src/generators/dom/visitors/EachBlock.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,16 +57,28 @@ export default function visitEachBlock ( generator, block, state, node ) {
}
` );

block.builders.update.addBlock( deindent`
if ( !${each_block_value}.length && ${each_block_else} ) {
${each_block_else}.update( changed, ${params} );
} else if ( !${each_block_value}.length ) {
${each_block_else} = ${node.else._block.name}( ${params}, ${block.component} );
${each_block_else}.mount( ${anchor}.parentNode, ${anchor} );
} else if ( ${each_block_else} ) {
${each_block_else}.destroy( true );
}
` );
if ( node.else._block.hasUpdateMethod ) {
block.builders.update.addBlock( deindent`
if ( !${each_block_value}.length && ${each_block_else} ) {
${each_block_else}.update( changed, ${params} );
} else if ( !${each_block_value}.length ) {
${each_block_else} = ${node.else._block.name}( ${params}, ${block.component} );
${each_block_else}.mount( ${anchor}.parentNode, ${anchor} );
} else if ( ${each_block_else} ) {
${each_block_else}.destroy( true );
}
` );
} else {
block.builders.update.addBlock( deindent`
if ( ${each_block_value}.length ) {
if ( ${each_block_else} ) ${each_block_else}.destroy( true );
} else if ( !${each_block_else} ) {
${each_block_else} = ${node.else._block.name}( ${params}, ${block.component} );
${each_block_else}.mount( ${anchor}.parentNode, ${anchor} );
}
` );
}


block.builders.destroy.addBlock( deindent`
if ( ${each_block_else} ) {
Expand Down
27 changes: 27 additions & 0 deletions test/runtime/samples/each-block-dynamic-else-static/_config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
export default {
data: {
animals: [ 'alpaca', 'baboon', 'capybara' ]
},

html: `
<p>alpaca</p>
<p>baboon</p>
<p>capybara</p>
`,

test ( assert, component, target ) {
component.set({ animals: [] });
assert.htmlEqual( target.innerHTML, `
<p>no animals</p>
` );

// trigger an 'update' of the else block, to ensure that
// non-existent update method is not called
component.set({ animals: [] });

component.set({ animals: ['wombat'] });
assert.htmlEqual( target.innerHTML, `
<p>wombat</p>
` );
}
};
5 changes: 5 additions & 0 deletions test/runtime/samples/each-block-dynamic-else-static/main.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{{#each animals as animal}}
<p>{{animal}}</p>
{{else}}
<p>no animals</p>
{{/each}}

0 comments on commit 6b2c927

Please sign in to comment.