Deleting a Sighting

Every so often a reported cryptid sighting turns out to be a hoax. While this may be rare, you do need a way to delete old or debunked data. Recall from Chapter 21 that destroying records is achieved by calling record.destroyRecord. Simple enough.

Make it so: Add a delete button to your template in app/templates/sighting/edit.hbs.

  <button type="submit" class="btn btn-info btn-block">Update</button>
  <button {{action 'cancel'}} class="btn btn-block">Cancel</button>
</form>

<hr>
<button {{action 'delete'}} class="btn btn-block btn-danger">
  Delete
</button>

In addition to the new button, you added a horizontal rule (a simple line) between the form elements to separate the Update and Cancel buttons from the new Delete button. The <hr> is a UI tool you are using to indicate that deleting a sighting is a separate process from editing a sighting.

Next, add the delete action to your controller, app/controllers/sighting/edit.js:

...
    cancel() {
      if(this.get('sighting').get('hasDirtyAttributes')){
        this.get('sighting').rollbackAttributes();
      }
      this.transitionToRoute('sightings');
    },
    delete() {
      var self = this;
      if (window.confirm("Are you sure you want to delete this sighting?")) {
        this.get('sighting').destroyRecord().then(() => {
          self.transitionToRoute('sightings');
        });
      }
    }
  }
});

The delete action adds a window.confirm to get the user’s confirmation. Aside from the conditional, this action is like the others: get the model, call a method, and add an async then to call when the API request is done.

Now navigate to http://localhost:4200/sightings and click the Edit button for one of your sightings to view the app/templates/sightings/edit.hbs and its new Delete button (Figure 24.5).

Figure 24.5  Edit Sighting form

Edit Sighting form

The cycle is now complete: creation to destruction.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.249.252