【问题标题】:Model doesn't update after record delete in Emberjs在 Emberjs 中删除记录后模型不更新
【发布时间】:2013-11-20 01:44:49
【问题描述】:

我实际上是在我的 Ember 应用程序中使用 Ajax 而不是 Ember-Data 来执行 CRUD 操作。

场景是每当我删除记录时,模型都不会更新。我有一个项目列表,每个项目前面都有一个“删除”按钮。

这是与删除相关的操作:

deleteItem: function(item){ //function for delete action
            var id = item.get('id');
            $.ajax({
                type : "POST",
                url : "http://pioneerdev.us/users/deleteProject/" + id,
                dataType : "json",
                success : function(data) {
                    console.log('success');
                }
            });
            alertify.success('Record Deleted!');
            window.setTimeout(function(){location.reload()},3000)
        }

如您所见,我正在使用location.reload 手动重新加载模型。如果有人感兴趣,他可以在我的 GitHub repo 上查看完整源代码

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: javascript ajax ember.js


    【解决方案1】:

    我用一些 cmets 更新了你的代码。希望对你有帮助。

    actions: {
      deleteItem: function(item){
        var id = item.get('id');
        var controller = this;
        $.ajax({
          type : "POST",
          url : "http://pioneerdev.us/users/deleteProject/" + id,
          dataType : "json",
          // use the success callback to safe notify the user when the record is deleted
          // in your current implementation the alert is displayed even if an error occurs in the server.
          success : function(data) {          
            // no need to location.reload, the removeObject will remove that item
            controller.removeObject(item);                    
            alertify.success('Record Deleted!');
          }
        });  
      }
    },
    filteredContent : function() {
      var searchText = this.get('searchText'), regex = new RegExp(searchText, 'i');
    
      return this.get('arrangedContent').filter(function(item) {
        return regex.test(item.projectname);
      });
      // instead of model use model.length so your template will update when some item is added or removed
    }.property('searchText', 'model.length')
    

    【讨论】:

    • 好的。触发成功了吗?
    • 触发成功,提示“记录已删除”但模型没有更新。
    • 我更新了答案,也许现在可以了。只需在计算属性 filteredContent 中将 model 更改为 model.length
    • 其实我也发现了别的东西,console.log('success') 也没有。
    • 触发成功处理程序时,该项目刚刚被删除。您可以进行测试并将成功处理程序的代码放在 ajax 调用之外。所以它总是会被执行。我们可以查看客户端是否正常,以及问题是否出在服务器上。我要睡觉了,明天再试试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多