我正在使用铁路由器将数据传递到引导模式模板。模态包含一个HTML表单,其中包含许多文本输入。模态被重新用于3个不同的功能。我使用Session变量来跟踪使用哪种模式类型。类型0 =空白表格,类型1 =部分编辑,类型2 =完整编辑。对于所有类型,表单本身在视觉上都保持不变。唯一更改的是哪个输入框包含一个值。
对于类型1,仅2个框将包含值。对于类型2编辑,所有框都将包含值。并且类型0将是空框。
// routes.js
Router.route('/mypage', function () {
var mtype = Session.get("mtype");
this.layout('myLayout');
this.render('my_popup', {to:'my_popup', data: function() {
switch (mtype) {
case 1:
return {box1:'box 1 text', box2:'box 2 text', box3:''};
case 2:
return {box1:'box 1 text', box2:'box 2 text', box3:'box 3 value'};
default:
return {box1:'', box2:'', box3:''};
}
}});
});
// main.html
<template name="myLayout">
{{> yield "my_popup"}}
</template>
<template name="my_popup">
<div class="modal fade" id="my_popup">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<div class="modal-title label label-primary">Title</div>
</div>
<div class="modal-body">
<form class="js-form-submit" id="my_form" name="my_form">
<div class="form-group">
<input class="form-control" type="text" name="box1" maxlength="64" placeholder="something" value="{{box1}}"/>
</div>
<div class="form-group">
<input class="form-control" type="text" name="box2" maxlength="64" placeholder="something" value="{{box2}}"/>
</div>
<div class="form-group">
<input class="form-control" type="text" name="box3" maxlength="64" placeholder="something" value="{{box3}}"/>
</div>
</form>
</div>
<div class="modal-footer">
<button class="js-form-ok btn btn-success btn-sm">submit</button>
<button class="btn btn-warning btn-sm" data-dismiss="modal">cancel</button>
</div>
</div>
</div>
</div>
</template>
最初,我尝试将对象传递给仅包含将要显示的属性的模式模板。那并没有覆盖现有的输入值,因此我必须为每种模式类型使用相同的对象,并为未使用的属性使用空字符串。在显示模式之前,我尝试在表单上调用reset()方法。在这种情况下,它将导致整个模板停止重新渲染。
在显示模态之前,我将会话变量设置为将要显示的模态类型。Session.set('mtype', 1);
这会触发铁路由器将适当的数据发送到模板,清除未使用的属性,然后成功重新渲染模板。
[不幸的是,如果我输入html输入之一,则模板在重新呈现时不会重置其值。这似乎与我在reset()方法中遇到的相同问题有关。如果输入包含自定义文本(键入值),那么在更改Session变量时,模式不会显示发送到模板的新数据。它保留用户输入的文本。
在流星中重用引导模态形式的最佳方法是什么?我应该使用助手而不是铁路由器来获取数据对象吗?有点像...
{{#with getData}}
为什么要保留用户输入的文本?
我也尝试使用defaultValue属性代替value。两个属性都发生相同的问题。
测试错误:
Session.set('mtype',1);
$('#my_popup').modal('show');
Session.set('mtype',0);
$('#my_popup').modal('show');
尽管您将键入的值发送给每个框都为空,但您仍会看到键入的值。
另一种方式:
Session.set('mtype',2);
$('#my_form')[0].reset();
Session.set('mtype',1);
$('#my_popup').modal('show');
尽管您已经向每个框发送了新的文本字符串,但是您不会看到任何框都包含值。
我发现的唯一解决方案是在模板中使用defaultValue,然后在显示模式并设置value = defaultValue之前遍历表单域。
<input class="form-control" type="text" name="box1" maxlength="64" placeholder="something" defaultValue="{{box1}}"/>
Template.my_popup.rendered = function() {
$("#my_popup").on('show.bs.modal', function() {
var elems = $('#my_form')[0].elements;
for (var i=0; i<elems.length; i++) {
if (elems[i].hasAttribute('defaultValue')) {
elems[i].value = elems[i].getAttribute('defaultValue');
}
}
});
};