流星,从父模板调用儿童模板中的功能

fab*_*ien 9 meteor meteor-blaze

如果我有一个Container带有子模板的父模板Contentavec只有一个按钮:

<head>
    <title>test</title>
</head>

<body>
    {{> Container}}
</body>

<template name="Container">
    {{# Content callback = callBack }}
        <button>ok</button>
    {{/Content}}
</template>

<template name="Content">
    {{> UI.contentBlock}}
</template>
Run Code Online (Sandbox Code Playgroud)

如果可以通过一个功能callback.像那样 :

Template.Container.helpers( {
    callBack: function () {
        return function () {
            console.log( 'this is my callback' );
        }
    }
} );
Run Code Online (Sandbox Code Playgroud)

所以在我的内容模板中,我可以从父模板中调用一个函数.比如这样:

Template.Content.events( {
    'click button': function ( e, tmpl ) {
        tmpl.data.callback();
    }
} );
Run Code Online (Sandbox Code Playgroud)

但有时候,我需要以另一种方式实现它.父母在他的孩子中调用一个函数.你这样做的方式是什么?


编辑:

我将它保存在一个meteorpad中以显示它的实际效果并使其易于分叉:http://meteorpad.com/pad/48NvCFExxW5roB34N/test-pass-callback-to-parent

use*_*348 16

这是你可以使用的模式.定义一个类Child和一个模板child; 我们的想法是,在child模板内部,数据上下文是一个Child实例.例如,我将创建一个具有可以通过按下按钮递增的数字的组件.

<template name="child">
  <button class="increment">{{number.get}}</button>
</template>
Run Code Online (Sandbox Code Playgroud)
function Child() {
  this.number = new ReactiveVar(0);
}

Template.child.events({
  "click .increment": function () {
    this.number.set(this.number.get() + 1);
  }
});
Run Code Online (Sandbox Code Playgroud)

在父级的created回调中,创建一个Child实例并将其存储在模板实例上.然后在父模板中调用child,传入Child作为数据上下文:

Template.parent.created = function () {
  this.childInstance = new Child();
}

Template.parent.helpers({
  childInstance: function () {
    return Template.instance().childInstance;
  }
});
Run Code Online (Sandbox Code Playgroud)
<template name="parent">
  {{> child childInstance}}
</template>
Run Code Online (Sandbox Code Playgroud)

现在,您可以在Child原型上定义方法并从父模板中调用它们,例如:

Child.prototype.getNumberTimesTwo = function () {
  return this.number.get() * 2;
}
Run Code Online (Sandbox Code Playgroud)
<template name="parent">
  {{> child childInstance}}
  That number multiplied by two is: {{childInstance.getNumberTimesTwo}}
</template>
Run Code Online (Sandbox Code Playgroud)