2013-07-30 40 views
0

我想從我通過jQuery.getJSON獲取的列表中刪除一個項目。只要尚不穩定,Ember數據並不是一個真正的選擇。Ember.js - 如何從沒有Ember-data的列表中刪除項目?

App.Project = Ember.Object.extend({ 
    remove: function() { 
     return $.ajax({ 
      url: '/api/v1/projects/'+this.get('id'), 
      type: 'DELETE' 
     }); 
    } 
}); 

App.Project.reopenClass({ 
    findAll: function() { 
     return jQuery.getJSON('/api/v1/projects').then(
      function(response) { 
       var projects = Ember.A(); 

       if (response.projects !== undefined) { 
        response.projects.forEach(function (project) { 
         projects.pushObject(App.Project.create(project)); 
        }); 
       } 

       return projects; 
      } 
     ); 
    } 
}); 

App.ProjectsRoute = Ember.Route.extend({ 
    model: function() { 
     return App.Project.findAll(); 
    }, 

    events: { 
     deleteProject: function(project) { 
      project.remove(); 
     } 
    } 
}); 

當我按下下面的按鈕時,它執行DELETE API調用,但它當然不會從數組中刪除項目。我怎樣才能從數組中刪除該項目?

<button class="btn btn-mini btn-danger" {{action 'deleteProject' this}}><i class="icon-trash"></i> Delete</button> 

回答

0

我認爲您正在尋找removeObject。

http://emberjs.com/api/classes/Ember.MutableEnumerable.html

你需要到你的項目控制內容的內容的引用,然後單個項目傳遞給方法的removeObject。

projects.removeObject(project);

+0

這的確看起來像我需要什麼,但我怎麼能得到一組的項目?我嘗試了'this.get('model')。removeObject(project)'但模型沒有這個方法。此外'this.get('content')'是* undefined *。 – EsTeGe

+0

看來我需要一個Ember.Set,但是當我將findAll方法轉換爲使用Ember.Set時,我得到一個Object [object Object]沒有方法'addArrayObserver'異常。 – EsTeGe

3

這裏是一個完全成熟的「燼數據免費」例如查找/添加/刪除

App.Person = Ember.Object.extend({ 
    id: null, 
    username: '' 
}); 

App.Person.reopenClass({ 
    people: [], 
    add: function(hash) { 
     var person = App.Person.create(hash); 
     this.people.pushObject(person); 
     $.ajax({ 
      type: "POST", 
      url: "/people/", 
      data: hash, 
      error: function() { 
       alert("create failed"); 
      }, 
      success: function(response) { 
       person.set('id', response.id); 
      } 
     }); 
    }, 
    remove: function(person) { 
     this.people.removeObject(person); 
     $.ajax({ 
      type: "DELETE", 
      url: "/people/" + person.id + "/", 
      error: function() { 
       alert("delete failed"); 
      } 
     }); 
    }, 
    find: function() { 
     var self = this; 
     $.getJSON('/people/', function(response) { 
      response.forEach(function(hash) { 
       var person = App.Person.create(hash); 
       Ember.run(self.people, self.people.pushObject, person); 
      }); 
     }, this); 
     return this.people; 
    } 
});