2015-10-11 2 views
2

У меня есть родительский шаблон, включенный с дочерним шаблоном. Мне нужно использовать родителей ReactiveVar из шаблона для детей. Я могу использовать метод Session, но для моего требования Session метод не работает. Как получить доступ к значению ReactiveVar из родительских шаблонов?Meteor ReactiveVar access parent tempate от дочернего шаблона

HTML:

<template name="ParentTemplate"> 
    {{> ChildTemplate}} 
</template> 

<template name="ChildTemplate"> 
//Some HTML content 
</template> 

JS

Template.ParentTemplate.onCreated(function() { 
    this.myvalue = new ReactiveVar(5); //I tried this.data.myvalue but doesnt works 
}); 
Template.ChildTemplate.helpers({ 
'myhelper' : function(){ 
    return Template.parentData(1).myvalue.get(); 
} 
}); 
+0

в родительском шаблоне, поместите данные в контекст 'Template.currentData()'. – MasterAM

ответ

5

Вот пример был ребенок является прямым потомком родителя:

<template name="parent"> 
    {{> child}} 
</template> 

<template name="child"> 
    <p>{{parentValue}}</p> 
</template> 

В этом случае мы может получить доступ к паре T в переменной экземпляра, как это:

Template.child.helpers({ 
    parentValue: function() { 
    var parentView = Blaze.currentView.parentView.parentView; 
    var parentInstance = parentView.templateInstance(); 
    // replace parentVariable with the name of the instance variable 
    return parentInstance.parentVariable.get(); 
    } 
}); 

Если два шаблона имеют более сложные отношения в DOM, вы можете использовать что-то вроде этого:

// replace .parent-class will the selector for your parent template 
el = $('.parent-class')[0] 
var parentInstance = Blaze.getView(el).templateInstance(); 
// replace parentVariable with the name of the instance variable 
return templateInstance.parentVariable.get(); 
+2

Большое спасибо. Ты мой учитель, который ответил на мои многочисленные вопросы. –

5

Другим возможным решением может быть, чтобы передать данные ребенок явно.

// js 
if (Meteor.isClient) { 
    Template.parent.onCreated(function() { 
     this.reactiveV = new ReactiveVar(42); 
    }); 

    Template.parent.helpers({ 
     getReactiveVar: function() { 
      return Template.instance().reactiveV; 
     }, 
    }); 

    Template.parent.events({ 
     'click button': function(e, tmp) { 
      tmp.reactiveV.set(tmp.reactiveV.get() + 2); 
     }, 
    }); 
} 

и в файле шаблона:

<template name="parent"> 
    <p>this is the parent!</p> 
    <button> var++ </button> 
    {{> child parentData=getReactiveVar}} 
</template> 


<template name="child"> 
    <h3> 
     child template 
    </h3> 
    {{parentData.get}} 
</template> 

, как вы нажмете на кнопку, вы увидите обновление шаблона ребенка. Если вам нужно, вы также можете назначить родительские данные каким-либо другим способом в функции Template.child.onCreated.

Это может обеспечить взаимозависимость между двумя шаблонами.

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