如何在Meteor中的不同模板之间传递响应变量? [英] How to pass Reactive variables among different templates in Meteor?

查看:72
本文介绍了如何在Meteor中的不同模板之间传递响应变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个单独的模板:

<template name = "MusicControl">
  <!-- Some Logics here -->
</template>

<template name = "MusicSystem">
  <!-- Some Logics here ("click" event) -->
</template>

我有2个与这2个模板相关联的JavaScript文件.

I have 2 JavaScript files associated with these 2 templates.

我想要的是,如果 MusicControl 模板上发生了一个事件("click"事件),它将设置某种全局变量(但 Session变量),以便我可以在另一个模板中访问它作为辅助函数.

What I want is that if an event occurs ("click" event) on the MusicControl template, it sets some sort of global variable (but not Session variable) so that I can access it in another template as a helper function.

如何在流星的反应区中实施?

别担心,我已经在各自的js中为两个模板定义了 helper函数.

Do not worry I have the helper functions defined for both the template in their respective js.

而且,这些<templates>是彼此独立的,我只想通过使用某种全局变量在template 2>上的<template 1>中监听事件.

And one thing, these <templates> are independent of each other, I just want to listen the event in <template 1> on <template 2> by using some sort of global variable.

推荐答案

@zim答案的简单版本是:

A simple version of @zim's answer is:

HTML(实际上是空格键)

<template name="Parent">
    {{> Child1 sharedVar1=sharedVar}}
    {{> Child2 sharedVar2=sharedVar}}
</template>

JavaScript

import { ReactiveVar } from 'meteor/reactive-var';

// Just initialize the variable. Could also be within the scope of a template.
var myReactiveVar = new ReactiveVar();

Template.Parent.helpers({
    // This is what will be sent to Child1 and Child2.
    sharedVar: function () {
        return myReactiveVar;
    }
});

Template.Child1.helpers({
    myValue: function () {
        // As usual, this will be reactive.
        return Template.instance().data.sharedVar1.get();
    }
});

Template.Child2.events({
    'event selector': function (event, template) {
        // This change will trigger an autorun of Child1 myValue helper.
        template.data.sharedVar2.set(myNewValue);
    }
});

(当然,您可以将它们拆分为几个JS文件)

(of course you can split these into several JS files)

使用Meteor 1.6.1和Blaze的演示应用程序示例: https: //github.com/ghybs/meteor-blaze-templates-share-data

Example with a demo app using Meteor 1.6.1 and Blaze: https://github.com/ghybs/meteor-blaze-templates-share-data

这篇关于如何在Meteor中的不同模板之间传递响应变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆