gpt4 book ai didi

meteor - meteor 中的模板重用

转载 作者:行者123 更新时间:2023-12-04 05:17:09 27 4
gpt4 key购买 nike

我正在尝试在我的 Meteor 应用程序中重用一些控制元素。我想要以下两个模板来切换不同表单的可见性和提交。

<template name='addControl'>
<img class='add' src='/images/icon-plus.png' />
</template>

<template name='okCancelControl'>
<img class='submit' src='/images/icon-submit.png' />
<img class='cancel' src='/images/icon-cancel.png' />
</template>

我将在另一个中调用这些模板:
<template name='insectForm'>
{{#if editing}}
<!-- form elements -->
{{> okCancelControl}}
{{else}}
{{> addControl}}
{{/if}}
</template>
editingSession bool 值。

连接控件以显示、隐藏和“提交”表单的好方法是什么?

最佳答案

主要问题是从控件模板(“提交”事件触发的地方)中找到 addInsect 模板(数据所在的地方)。这是我所做的:

一、控件:

<template name='addControl'>
<section class='controls'>
<span class="add icon-plus"></span>
</section>
</template>

<template name='okCancelControl'>
<section class='controls'>
<span class="submit icon-publish"></span>
<span class="cancel icon-cancel"></span>
</section>
</template>

现在是javascripts。他们只是在点击时调用回调。
Template.addControl.events({
'click .add': function(event, template) {
if (this.add != null) {
this.add(event, template);
}
}
});

Template.okCancelControl.events({
'click .cancel': function(event, template) {
if (this.cancel != null) {
this.cancel(event, template);
}
},
'click .submit': function(event, template) {
if (this.submit != null) {
this.submit(event, template);
}
}
});

然后我使用 Handlebars 的 #with 连接回调块 helper 。
<template name='addInsect'>
{{#with controlCallbacks}}
{{#if addingInsect}}
<section class='form'>
{{> insectErrors}}
<label for='scientificName'>Scientific Name <input type='text' id='scientificName' /></label>
<label for='commonName'>Common Name <input type='text' id='commonName' /></label>
{{> okCancelControl}}
</section>
{{else}}
{{> addControl}}
{{/if}}
{{/with}}
</template>

以及创建与此表单相关的回调的相应 javascript。
Session.set('addingInsect', false);

Template.addInsect.controlCallbacks = {
add: function() {
Session.set('addingInsect', true);
Session.set('addInsectErrors', null);
},
cancel: function() {
Session.set('addingInsect', false);
Session.set('addInsectErrors', null);
},
submit: function() {
var attrs, errors;
attrs = {
commonName: DomUtils.find(document, 'input#commonName').value,
scientificName: DomUtils.find(document, 'input#scientificName').value
};
errors = Insects.validate(attrs);
Session.set('addInsectErrors', errors);
if (errors == null) {
Session.set('addingInsect', false);
Meteor.call('newInsect', attrs);
}
}
};

Template.addInsect.addingInsect = function() {
Session.get('addingInsect');
};

Template.addInsect.events = {
'keyup #scientificName, keyup #commonName': function(event, template) {
if (event.which === 13) {
this.submit();
}
}
};

在提交回调中,我必须使用 DomUtils.find而不是 template.find因为 template是 okCancelControl 的实例,而不是 addInsect。

关于meteor - meteor 中的模板重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14098662/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com