AngularFire $firebaseObject.$cancel()

Stephan Smith
d1b1
Published in
2 min readAug 10, 2017

I have run into a simple and rather common sense request from a client. Can I cancel my changes? This is such a simple and straight forward ask, that I said ‘yes’ before thinking through a solution.

It seems AngularFire is setup to provide bindings, but appears to lack the option to tell me which fields have changed, or cancel local changes to the object. Backbone.js has the option to get changed data values. This is the first time in years, after making the move to angular, that I missed a features from my BB days.

The Problem

A user reviews a list of ($firebaseArray) of values. And then uses a Modal Dialog to edit a specific item. As the user edits the name, description etc. The user can see the model change in table behind the Modal. When the user ‘Saves Changes’ the $firebaseObject.$save() is triggered and the modal is closed.

If the user edits, via the form input value, the name and description, but decided not to save, and closed the modal, the changes are still visible in the table. The user will, logically, think that the changes are preserved. But a hard refresh will show that without the $save in the modal, nothing was saved. This has lead to a number of user complaints.

A Basic Solution

To make the UI and Modal match the user’s expected behaviors, I altered the UI Modal to call a new method of the $firebaseObject.$cancel. This method is added to the object by extending the $firebaseObject.

Here is the extended BookFactory with the $cancel method.

Here is the Modal and the $scope event to trigger the $cancel method.

This solution simple uses the $firebaseObject ref, and does a single .once(‘value’) call from Firebase, then update the object key by key. Not certain this is the best approach, but it get the job done. If the user click ‘Save’ the changes are save, the modal closes and the list of objects reflects the UI changes. If the user chooses the ‘Cancel’ button, then the object data is reset and the table shows the current date of the array data.

$firebaseObject Method Wish List

I am not a contributor to the AngularFire project. Assuming the following do not violate the library mission, I would love to see the following:

  • $firebase.changes() — Returns an array of fields changed. i.e. ([ ‘name’, ‘description’ ]
  • $firebase.hasChanged() — Returns a boolean if there are local changes to the object.

If you think this makes sense, please add in github +1. Here is my issue asking about better ways to handle. Github Issue.

--

--

Stephan Smith
d1b1
Editor for

Startup founder — Boston based full stack developer with a strong focus on rapid prototyping, server-less solutions, and testable code.