【问题标题】:Re-render Blaze template on text change在文本更改时重新渲染 Blaze 模板
【发布时间】:2017-03-13 04:50:39
【问题描述】:

我有一个基于 autoform 的 Meteor Blaze 模板。

<template name="patientForm">

<div class='mdl-cell mdl-cell--12-col'>
    {{#autoForm id="insertUpdatePatientForm" collection="Patients" doc=selectedPatientDoc
    type=formType validation="browser" template="semanticUI"}}
    <div class='two fields'>
    {{> afQuickField name="firstName"}}
    {{> afQuickField name="lastName"}}
    </div>
    <div class='two fields'>
   {{> afQuickField name="phn.type"}}
   {{> afQuickField name="phn.value" class="ramq"}}
   </div>
       <div class='two fields'>
        {{> afQuickField name="birthDate"}}
        {{> afQuickField name="gender"}}
       </div>

    <button class="ui submit button" type="submit">Save</button>
    <div class="ui error message"></div>
    {{/autoForm}}
</div>
</template>

我想处理名称为 phn.value 的输入的文本更改事件。根据文本,我想自动填充另外两个字段:性别和出生日期。我是通过直接更改模板数据来实现的,如下所示:

Template.patientForm.events({
    'change .ramq': function changeRAMQ(event, templateInstance) {
        const { patient } = templateInstance.data;
        if (patient.phn.type === 'RAMQ') {
            const ramq = event.target.value;
            const yy = parseInt(ramq.substr(4, 2), 10);
            let mm = parseInt(ramq.substr(6, 2), 10);
            const dd = parseInt(ramq.substr(8, 2), 10);
            patient.gender = mm < 13 ? 'Male' : 'Female';
            if (mm > 50) {
                mm -= 50;
            }
            patient.birthDate = moment(new Date(yy, mm, dd)).format('YYYY-MM-DD');
        }
    },
});

当 phn.value 发生变化时,我正在获取模板数据并直接修改性别和出生日期。但是,修改后的性别和出生日期不会在 autoform / blaze 模板中重新渲染。有什么方法可以强制重新渲染 Blaze 模板或替代方法来影响对 Blaze 模板中其他控件的更改?

【问题讨论】:

    标签: meteor meteor-blaze meteor-autoform


    【解决方案1】:

    要启用反应性并因此重新呈现字段,您应该使用 ReactiveVar(或 ReactiveDict)

    你可以这样做:

    Template.patientForm.onCreated(function(){
      const instance = this;
      instance.birthDate = new ReactiveVar()
    });
    

    在你的助手和事件中你可以使用 instance.birthDate.set() / get()

    Template.patientForm.helpers({
       birthDate() {
          return Template.instance().birthDate.get()
       }
    });
    
    Template.patientForm.events({
       'click something'(event, instance){
       ....
         instance.birthDate.set(value);
       ....
       }
    });
    

    【讨论】:

      【解决方案2】:

      您不能直接修改模板数据(可以,但这不是反应性的,会被覆盖)。您从哪里获取模板数据?收藏?一个反应变量?如果是这样,请修改那里的数据 -- Blaze 会注意到更改并重新渲染。

      据说这样的事情会起作用:

      Patients.update(templateInstance.data._id, {$set: {
        birthDate: ..,
        gender: .. 
      }});
      

      【讨论】:

      • 这是 addPatient 表格。我想根据文本框的值自动填充另外两个字段。
      猜你喜欢
      • 2020-07-07
      • 2017-07-18
      • 2014-03-14
      • 1970-01-01
      • 2014-06-14
      • 2018-04-20
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      相关资源
      最近更新 更多