2013-03-16 4 views
0

handlebars.js에서 컨텍스트가 작동하는 방식, 특히 "../"표기법을 이해하는 데 문제가 있습니다. 이것은 가장 jsfiddle을들 수있다 내가 함께 넣어 :handlebars.js 컨텍스트를 이해하는 데 문제가 있습니다.

http://jsfiddle.net/accelerate/AwChe/

상황 :

"rootvar": "hi", 
"mydata": [{ 
    "renderme": true, 
    "mytext": "bye" 
}] 

템플릿 :

rootvar = {{{rootvar}}} (should be "hi")<br/> 
{{#each mydata}} 
<br/>In mydata...<br/> 
rootvar = {{{rootvar}}} (should be empty)<br/> 
rootvar = {{{../rootvar}}} (should be "hi")<br/> 
mytext = {{{mytext}}} (should be "bye")<br/> 
{{#if renderme}} 
<br/>In renderme...<br/> 
rootvar = {{{rootvar}}} (should be empty)<br/> 
rootvar = {{{../rootvar}}} (should be empty)<br/> 
rootvar = {{{../../rootvar}}} (should be "hi")<br/> 
mytext = {{{mytext}}} (should be empty!!)<br/> 
mytext = {{{../mytext}}} (should be "bye")<br/> 
{{/if}} 
{{/each}} 

출력 :

rootvar = hi (should be "hi") 

In mydata... 
rootvar = (should be empty) 
rootvar = hi (should be "hi") 
mytext = bye (should be "bye") 

In renderme... 
rootvar = (should be empty) 
rootvar = (should be empty) 
rootvar = hi (should be "hi") 
mytext = bye (should be empty!!) 
mytext = bye (should be "bye") 

즉, #if 문이 #each 문 내에 중첩되어 있습니다. 왜 "../../rootvar"를 사용하여 "rootvar"에 액세스해야하는지 알 수 있습니다. 내가 이해하지 못하는 이유는 현재 mydata 요소 내의 다른 변수에 액세스하기 위해 "../"을 수행 할 필요가 없기 때문입니다. "rootvar"처럼 "mytext"에 액세스하려면 # if의 상위 컨텍스트로 이동해야합니까? 그리고 만약 내가하지 않는다면, 왜 "../mytext"도 작동합니까?

답변

1

문맥을 유지하기 때문에 도우미는 정상적으로 #if입니다.

//here context is: 
// "rootvar": "hi", 
// "mydata": [{ 
// "renderme": true, 
// "mytext": "bye" }] 
rootvar = {{{rootvar}}} (should be "hi")<br/> 
{{#each mydata}} 
// here `each` will change the context to each item in 'mydata' so it becomes 
// { "renderme": true, 
//  "mytext": "bye" } 
<br/>In mydata...<br/> 
rootvar = {{{rootvar}}} (should be empty)<br/> 
rootvar = {{{../rootvar}}} (should be "hi")<br/> 
mytext = {{{mytext}}} (should be "bye")<br/> 
{{#if renderme}} 
// now `if` will create new context but it is the same as the parent context 
//  { "renderme": true, 
//  "mytext": "bye" } 
<br/>In renderme...<br/> 
rootvar = {{{rootvar}}} (should be empty)<br/> 
rootvar = {{{../rootvar}}} (should be empty)<br/> 
rootvar = {{{../../rootvar}}} (should be "hi")<br/> 
mytext = {{{mytext}}} (should be "bye")<br/> 
mytext = {{{../mytext}}} (should be "bye")<br/> 
{{/if}} 
{{/each}} 

자세한 내용은 github issue을 참조하십시오.

+0

고마워요! 당신의 설명은 완전히 의미가 있습니다. – accelerate

관련 문제