如何在没有Ember数据的情况下从列表中删除项目?

时间:2013-07-30 08:34:29

标签: ember.js

我正在尝试从通过jQuery.getJSON获取的列表中删除项目。只要它不稳定,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>

2 个答案:

答案 0 :(得分:3)

以下是查找/添加/删除

的完整版“ember-data free”示例
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;
    }
});

答案 1 :(得分:0)

我认为您正在寻找removeObject

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

您需要获取对项目控制器内容的内容的引用,然后将单个项目传递给removeObject方法。

projects.removeObject(project);