簡體   English   中英

流星應用程序的雙向數據綁定

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM