2017-10-10 107 views
1

场景:呼叫Meteor.call()和wait里面`前:insert`挂钩

我试图插入一个Appointment使用autoform只有当日期不冲突的客户端。下面是获取简要想法的代码。

{{#autoForm id='insertAppointmentForm' collection=appointment type="insert" 
       doc=this validation="browser"}} 
    <fieldset> 
     <!-- All fields here --> 
    </fieldset> 
    <button type="submit" class="btnn"> Create </button> 
{{/autoForm}} 

我加入钩上面自动窗体如下insert代码,

var hooksObject = { 
    before: { 
    insert: function(doc) { 
     console.log(doc); 
     Meteor.call('checkAppointmentClash', doc, function(error, response){ 
      if(error){ } else { } 
     }); 
     return doc; // I want to wait here 
    } 
    }, 
    onSuccess: function(formType, result) {}, 
    onError: function(formType, error) {} 
}; 

AutoForm.addHooks(['insertAppointmentForm'], hooksObject, true); 

问题:

这里的问题是,表单被提交即使errorMeteor.call()和插入返回到数据库的document。我知道Meteor.call()是异步调用,但我如何等待结果呢?只有这样我才能继续提交,如果没有错误。

回答

2

挂钩可以异步工作。来自documentation

如有必要,这些函数可以执行异步任务。如果不需要异步性,只需返回文档或修改器,或返回false以取消提交。如果您不返回任何内容,则最终必须致电this.result(),并将其传递给文档或修改器,或者通过false取消提交。

因此,代码看起来是这样的:

insert: function(doc) { 
    // note using() => {} to bind `this` context 
    Meteor.call('checkAppointmentClash', doc, (error, response) => { 
    if(error) { 
     this.result(false); 
    } else { 
     this.result(doc); 
    } 
    }); 
    // return nothing 
} 

虽然,我建议你重新考虑你的流量。检查钩子中的“冲突”是错误的。您应该在“用户输入的数据”步骤中执行此操作,并相应地禁用/启用“提交”按钮。

+0

检查“用户输入数据”的冲突在性能方面没有可行的解决方案(即使我使用'_.debounce'来控制请求)。在钩子上检查它只需调用一次服务器,它适合我的应用程序需求。 –

+0

@AnkurSoni当用户已经在现场输入数据时,我并不是指“连续检查”,只是一次。当然,如果你需要_all_字段来检查冲突,那就没有意义了:) – Styx