2013-03-08 13 views
8

Non so come trattare con serie ricorsiva in template.and non riesco a trovare nulla nella documentazione di handlebarsjsCome usare il modello ricorsivo?

ci sono i miei codici: JS:

 

    var branch = [{ 
       name:"firstLayerNodeA", 
       has_branch:true, 
       branch:[{ 
         name:"secondLayoutNodeA", 
         has_branch:false 
        },{ 
         name:"secondLayoutNodeB", 
         has_branch:true, 
         branch:[{ 
           name:"thirdLayerNodeA", 
           has_branch:true, 
           branch:[{ 
             //fourth Layer 
             //fifth Layer 
             //..... 
           }] 
         }] 
       }] 
      },{ 
       name:"firstLayerNodeB", 
       has_branch:false 
      }] 

html

<Template name="tree"> 
    <ul> 
    {{#each brach}} 
     <li> 
     name 
     {{#if has_branch}} 
      <ul> 
      {{#each brach}} 
       <li> 
       name 
       {{#if has_brach}} 
         {{#each brach}} 
          .....third layer 
          .....fourth layer 
          .... 
         {{/each}} 
       {{/if}} 
       </li> 
      {{/each} 
      </ul> 
     {{/if}} 
     </li> 
    {{/each}} 
    </ul> 
</Template> 

Ci sono buone idee che riguardano il ramo nel modello? Qualsiasi aiuto è apprezzato.

risposta

4

È possibile utilizzare i modelli annidati:

lato client js

Template.tree.branch = function() { 
    var branch = ... 
    return branch; 
} 

Html

<template name="tree"> 
    <ul> 
    {{#each branch}} 
     <li>  
     {{>branch}} 
     </li>  
    {{/each}} 
    </ul> 
</template> 

<template name="branch"> 
    {{name}} 
    {{#if branch.length}} 
     <ul> 
      {{#each branch}} 
       <li> 
        {{>branch}} 
       </li> 
      {{/each}} 
     </ul> 
    {{/if}} 
</template> 

Inoltre non si ha realmente bisogno has_branch. Basta controllare la lunghezza dell'array di ramificazioni invece che ognuna andrà in loop solo se è un array e c'è del materiale

+0

Grazie per il vostro tempo. questa è una buona idea! –

2

Akshat's answer è molto buono. Tuttavia, usandolo ho avuto qualche problema con la gestione degli eventi. L'evento è stato catturato più volte; una volta per ogni istanza del modello branch che conteneva l'elemento di lancio dell'evento.

Non è sicuro se si tratta di un bug o di una caratteristica ... comunque ho potuto superare utilizzando:

Template.branch.events({ 
    'click': function (e,b) {  
    console.log("this will show up as often as deep your tree is"); 
    if (this._id==b.data._id) 
     console.log("this will show up only once"); 
    } 
}); 
+1

È possibile evitare questo utilizzando e.stopPropagation() – ivan133

+0

Penso che non abbia funzionato o meno come previsto quando ho scritto la risposta ... @ ivan133 hai effettivamente testato se lo fa ora? –

+0

sì, ho testato id prima di postare un commento. – ivan133

Problemi correlati