2014-10-22 3 views
0

У меня была проблема, когда я использовал рекурсивные частичные части. Я пытался создать комментарии, которые каждый может высказаться еще раз, как это:Активные рекурсивные партитуры со смещением

comment (depth 0) 
    comment (depth 1) 
    comment (depth 2) 

Я хочу добавить некоторые специальные классы для различной глубины комментариев

{{#messages}} 
     {>message} 
    {{/messages}} 
    <!-- {{>message}} --> 
    <div class="{{getClasses()}}"">{{text}}</div> 
     {{incrDepth()}} 

     {{#comments}} 
     {{>message}} 
     {{/comments}} 

     {{decrDepth()}} 
    <!-- {{/message}} --> 

Это дополнительная функция, которую я использую

{ 
    data: { 
    incrDepth: function() { 
     this.depth++; 
    }, 

    decrDepth: function() { 
     this.depth--; 
    }, 

    getClasses: function() { 
     return 'depth' + this.depth; 
    } 
    } 
} 

Итак, перед каждым комментарием я увеличиваю глубину и после комментариев уменьшаю его. Но, к сожалению, все мои призывы getClasses() возвращают 'depth0', и я не могу понять почему.

ответ

3

Это помогает, если вы считаете, что шаблоны являются только для чтения, а не «исполнением» шаблона сверху вниз, Ractive создает виртуальный DOM из шаблона и обновляет узлы в нем, когда им нужно изменить. По этой причине нет никакой гарантии, когда будет вызвана данная функция.

Поэтому вам следует избегать функций с «побочными эффектами» - они должны быть для извлечения данных, никогда не устанавливая его.

Но рекурсивная структура определенно возможна - вам необходимо использовать встроенные компоненты. Компонент представляет собой вложенный Ractive-экземпляр, который управляет своими собственными данными, и легко установить свойство depth на «независимо от того, какой родительский depth есть, плюс один» - попробуйте выполнить снимок кода ниже, чтобы увидеть его в действии.

Ractive.components.comment = Ractive.extend({ 
 
    template: '#comment', 
 
    data: { depth: 0 } // default 
 
}); 
 

 
var ractive = new Ractive({ 
 
    el: 'main', 
 
    template: '#template', 
 
    data: { 
 
     comments: [ 
 
      { 
 
       author: 'alice', 
 
       content: 'FIRST!' 
 
      }, 
 
      { 
 
       author: 'bob', 
 
       content: 'first!!1!', 
 
       children: [ 
 
        { 
 
         author: 'bob', 
 
         content: 'argh alice beat me', 
 
         children: [ 
 
          { 
 
           author: 'alice', 
 
           content: 'haha' 
 
          }, 
 
          { 
 
           author: 'charles', 
 
           content: 'you snooze you lose' 
 
          } 
 
         ] 
 
        } 
 
       ] 
 
      }, 
 
      { 
 
       author: 'larry_34xj', 
 
       content: 'Thank you for this article, it is very interesting. Please visit my blog at http://pills4u.com' 
 
      }, 
 
      { 
 
       author: 'dawn', 
 
       content: 'This article is terrible. I don\'t know where to begin', 
 
       children: [ 
 
        { 
 
         author: 'bob', 
 
         content: 'do you have nothing better to do than write snarky comments on blog posts?', 
 
         children: [ 
 
          { 
 
           author: 'dawn', 
 
           content: 'Do you have nothing better to do than write "first"? loser', 
 
           children: [ 
 
            { 
 
             author: 'bob', 
 
             content: 'touché' 
 
            }, 
 
            { 
 
             author: 'alice', 
 
             content: 'haha pwned' 
 
            } 
 
           ] 
 
          } 
 
         ] 
 
        } 
 
       ] 
 
      }   
 
     ] 
 
    } 
 
});
body { font-family: 'Helvetica Neue', arial, sans-serif; font-weight: 200; color: #353535; } h1 { font-weight: 200; } p { margin: 0.5em 0; } 
 

 
.comment { 
 
    padding: 0.5em; 
 
    border-top: 1px solid #eee; 
 
} 
 

 
.comment .comment { 
 
    padding-left: 2em; 
 
} 
 

 
.depth-1 { 
 
    color: #555; 
 
} 
 

 
.depth-2 { 
 
    color: #999; 
 
}
<script src="http://cdn.ractivejs.org/latest/ractive.js"></script> 
 

 
<main></main> 
 

 
<script id='template' type='text/ractive'> 
 
    <h1><a href='http://ifyoulikeitsomuchwhydontyougolivethere.com/' target='_blank'>spEak You're bRanes</a></h1> 
 
    
 
    {{#each comments}} 
 
     <comment comment='{{this}}'/> 
 
    {{/each}} 
 
</script> 
 

 
<script id='comment' type='text/ractive'> 
 
    <article class='comment depth-{{depth}}'> 
 
     <p><strong>{{comment.author}}</strong> wrote:</p> 
 
     <p>{{comment.content}}</p> 
 
     
 
     {{#each comment.children}} 
 
      <comment comment='{{this}}' depth='{{depth + 1}}'/> 
 
     {{/each}} 
 
    </article> 
 
</script>

Смежные вопросы