【问题标题】:transition after saving model of ember data保存 ember 数据模型后的转换
【发布时间】:2013-02-20 13:50:35
【问题描述】:

我想在创建帖子后进行转换。

post/new > 点击提交 > rails 后端成功创建帖子并响应一个 json > 重定向到新创建的帖子路径

在 ember_data_example github 源代码中。他们使用这种方法

 transitionAfterSave: function() {
     // when creating new records, it's necessary to wait for the record to be assigned
     // an id before we can transition to its route (which depends on its id)
     if (this.get('content.id')) {
       this.transitionToRoute('contact', this.get('content'));
     }
 }.observes('content.id'),

很好用,因为模型创建时模型ID为null,模型保存成功后模型ID会发生变化,因为该函数会观察模型ID的变化。

但也许,只要模型的 ID 属性发生更改,就会执行此函数。 我正在寻找一些更语义化的方式。

我想要执行转换 当模型的状态变为 'isDirty' = false && 'isNew' == true form 'isDirty' = true, 'isNew' = false。

我该如何实现?

【问题讨论】:

    标签: ember.js ember-data


    【解决方案1】:

    理想情况下,id 不应该改变。但是,您是对的,从语义上讲,这种方法似乎不对。

    有一种更简洁的方法可以做到这一点:

    save: function(contact) {
      contact.one('didCreate', this, function(){
        this.transitionToRoute('contact', contact);
      });
    
      this.get('store').commit();
    }
    

    2013 年 11 月 27 日更新(ED 1.0 测试版):

    save: function(contact) {
      var self = this;
      contact.save().then(function() {
        self.transitionToRoute('contact', contact);
      });
    }
    

    【讨论】:

    • 谢谢,这正是我需要的!
    • 我错过了什么吗?我有一个保存功能作为表单上的操作,但是传递给我的异常函数的参数是未定义的。所以我不能调用 one() 。
    • 是的,你需要传递带有动作的模型,例如:<form {{action save model on="submit"}}>
    • 我相信这不再起作用了,因为现在 Ember 会在模型相同的情况下产生无操作转换。正在寻找解决方案。
    • 同款为什么要转场?
    【解决方案2】:

    Ember 2.4 的注意事项 它被鼓励在组件或路由级别处理保存操作(并避免使用控制器)。下面是一个例子。请注意转换中模型对象上的 id。并注意我们如何在路由中使用 transitionTo 而不是 transitionToRoute。

      actions: {
        save() {
          var new_contact = this.modelFor('contact.new');
          new_contact.save().then((contact) => {
            this.transitionTo('contact.show', contact.id);
          });
        },
    

    【讨论】:

      【解决方案3】:
          actions: {
              buttonClick: function () {
                  Ember.debug('Saving Hipster');
                  this.get('model').save()
                      .then(function (result) {
                          this.transitionToRoute('hipster.view', result);
                      }.bind(this));
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2022-11-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-17
        • 2017-02-03
        相关资源
        最近更新 更多