【问题标题】:Binding ember model in dynamically generated form以动态生成的形式绑定 ember 模型
【发布时间】:2017-04-24 04:34:40
【问题描述】:

我最近几周正在学习 ember js,并构建了一个应用程序来学习它。我处于必须构建一个动态表单的情况,该表单将绑定到 ember 模型。 (这个问题最简单的例子可能是嵌套表单,我们可以点击添加更多链接/按钮来动态添加表单,并为它们添加值)。

但对我来说,我正在构建类似网站的调查,我们可以在其中有很多选项可供选择,用户可以从可用选项中选择一个:

到目前为止我做了什么?

readAnswer: Ember.computed(function() {
    return this.get('store').query('answer', { filter:
      {
        question_id: this.get('question.id'),
        submission_id: this.get('submission.id')
      }
    })
  }),

  buildAnswer: Ember.computed(function() {
    this.get('store').createRecord('answer', {
      question: this.get('question'),
      submission: this.get('submission')
    })
  }),

  answer: Ember.computed(function() {
    const ans = this.get('readAnswer');
    console.log(`question_id: ${this.get('question.id')}, submission_id:     ${this.get('submission.id')}`);
    if(Ember.isEmpty(ans)) {
      return this.get('buildAnswer');
    } else {
      return ans;
    }
  })

answer.hbs

<div class="row col-sm-12">
  <div class="form-group">
    <label>{{model.title}}</label>
    <p>
      {{input type="text" value=answer.field01 class="form-control" placeholder="width"}}
    </p>
    <p>
      {{input type="text" value=answer.field02 class="form-control" placeholder="depth"}}
    </p>
  </div>
</div>

注意这里 answer.hbs 是一个组件,这些是从父路由递归(循环)调用的。所以对于 2 个问题,我们可以有 4 个文本框,每个问题有 2 个文本框,第一个文本框用于 answer.field01,第二个文本框用于 answer.field02

假设我有 2 个问题,到目前为止,如果数据库中不存在 2 个答案,我可以在 ember 商店中看到它们,然后,我可以看到在视图中生成了 4 个文本框。但它们没有约束力。意思是,如果我可以对文本框进行赋值,则 ember 商店中不会发生任何事情。

预期结果

当我在文本框中输入答案时,它应该与 answer.fieldxx 正确绑定。

【问题讨论】:

    标签: ember.js ember-cli rails-api


    【解决方案1】:

    我从computed propertyinit() 函数中提取了这些代码,现在一切正常:

      answer: null,
    
      init() {
        this._super(...arguments);
    
        // build without computed property
        this.get('store').query('answer', { filter:
          {
            question_id   : this.get('question.id'),
            submission_id : this.get('submission.id')
          }
        }).then((answers) => {
          if(Ember.isEmpty(answers)) {
            let a = this.get('store').createRecord('answer', {
              question   : this.get('question'),
              submission : this.get('submission')
            })
            this.set('answer', a); // build new object and set answer
          } else {
            this.set('answer', answers.get('firstObject')); // get first answer and build it (because it is always 1 record)
          }
        }, (reason) => {
          console.log(reason);
        });
      },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-25
      • 1970-01-01
      • 2017-06-20
      相关资源
      最近更新 更多