[英]Two-way data binding for a Meteor app
我建立了一个基于表单的应用程序。 我想让用户部分填写表格,如果他们目前无法完成,请稍后再回来。 我已经使用Iron Router为每个表单实例创建一个唯一的URL,因此它们可以返回到链接。 我的问题是,Meteor不会自动将值保存在输入中,并且在重新访问/刷新时,该表单将变为空白。 我尝试了以下解决方案,将数据存储在名为“ NewScreen”的单独的Mongo集合中的临时文档中,然后每次(重新)渲染模板以自动填写表单时,都引用该文档。 但是,我一直收到一个错误,我要引用的元素是“未定义”。 奇怪的是,有时它起作用,有时却不起作用。 我尝试设置一个递归setTimeout函数,但是在失败的时候,这也不起作用。 任何见识将不胜感激。 或者,如果我要解决所有这些错误,请随时提出另一种方法:
Screens = new Meteor.Collection('screens') //where data will ultimately be stored
Forms = new Meteor.Collection('forms') //Meteor pulls form questions from here
NewScreen = new Meteor.Collection('newscreen') //temporary storage collection
Roles = new Meteor.Collection('roles'); //displays list of metadata about screens in a dashboard
//dynamic routing for unique instance of blank form
Router.route('/forms/:_id', {
name: 'BlankForm',
data: function(){
return NewScreen.findOne({_id: this.params._id});
}
});
//onRendered function to pull data from NewScreen collection (this is where I get the error)
Template.BlankForm.onRendered(function(){
var new_screen = NewScreen.findOne({_id: window.location.href.split('/')[window.location.href.split('/').length-1]})
function do_work(){
if(typeof new_screen === 'undefined'){
console.log('waiting...');
Meteor.setTimeout(do_work, 100);
}else{
$('input')[0].value = new_screen.first;
for(i=0;i<new_screen.answers.length;i++){
$('textarea')[i].value = new_screen.answers[i];
}
}
}
do_work();
});
//onChange event that updates the NewScreen document when user updates value of input in the form
'change [id="on-change"]': function(e, tmpl){
var screen_data = [];
var name = $('input')[0].value;
for(i=0; i<$('textarea').length;i++){
screen_data.push($('textarea')[i].value);
}
Session.set("updateNewScreen", this._id);
NewScreen.update(
Session.get("updateNewScreen"),
{$set:
{
answers: screen_data,
first: name
}
});
console.log(screen_data);
}
如果undefined
,则可能意味着findOne()找不到包含从URL传递来的ID的新屏幕。 要对此进行调查,请添加一条额外的行,例如console.log(window.location.href.split('/')[window.location.href.split('/').length-1], JSON.stringify(new_screen));
这将为您提供URL中的ID和找到的new_screen。
我建议您使用Router.current().location.get().path
而不是window.location.href
因为您使用IR。
如果您要在客户端中寻找两种方式的绑定,请查看Viewmodel for Meteor 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.