Search code examples
ember.jsfirebaseember-dataemberfire

Emberfire destroyRecord error


I am currently receiving todo is not defined when I try to call the destoryRecord method on an item in my store. I have tried to rewrite this code a number of ways but i still seem to be running into problems.

Here are the files I am working with. It posts records just fine, but I just keep running into a problem with deleting them.

// todo/controller.js
import Ember from 'ember';
export default Ember.Controller.extend({
    actions: {
        createTodo: function() {
            this.store.createRecord('todo', {
            name: this.get('name'),
            createdAt: new Date()
        });
        this.set('name', '');
        },
        removeTodo: function() {
        this.store.find('todo', todo).then(function(todo) {
            todo.destroyRecord();
            });
        }
    }
});





// todo/model.js
import DS from 'ember-data';
export default DS.Model.extend({
    name: DS.attr('string'),
    createdAt: DS.attr('date')
});



// todo/route.js
import Ember from 'ember';
export default Ember.Route.extend({
    model: function() {
        return this.store.findAll('todo');
     }
   });

// todo/template.hbs
{{outlet}}
<div class="jumbotron">
    <h2 class="text-center">Add a Todo!</h2>
</div>
<div class="row">
    <div class="col-sm-10 col-sm-offset-1">
<div class="panel panel-default">
    <div class="panel-heading">
    <label for="Todo">Add a Todo!</label>
    {{input value=name placeholder="Add a Todo"}}
   <button class="btn btn-default" {{action "createTodo"}}>Publish</button> 
    </div>
    {{#each model as |todo|}}
        <div class="panel-body">
        <ul>
    <li>
        <button class="btn btn-default" {{action "removeTodo"}}>x</button>  
    {{todo.name}}</li>
    </ul>
        </div>
    {{/each}}
        </div>
    </div>
</div>

Solution

  • The removeTodo function has a problem, the todo variable passed to the find function is not defined anywhere.

    removeTodo: function() {
        this.store.find('todo', todo /* Where is this coming from */).then(function(todo) {
            todo.destroyRecord();
            });
        }
    

    You need the following changes to the template:

    {{action "removeTodo" todo}}
    

    The previous changes makes the todo which is available in the each as |todo| to be passed to the action removeTodo

    And you need to change the removeTodo function to this

    removeTodo: function(todo) {
        todo.destroyRecord();
    }
    

    Now that it receives the todo used in the context of the iteration you can use it in the function and call destroyRecord on it.