0

I have an object that represents a restaurant order:

function order () {
  this.customer_name = ''
  this.menu = // menu object
  }

extended with some object methods for business logic, like:

order.prototype.value = function() {
  var total = 0;
  for (var i = 0; i < this.menu.length; i++) {
    // calculate the order value
  }
  return total;
}

In the angular controller orders get pushed onto an array when submitted (via ng-click from a button in the view):

var ref = new Firebase('https://myfirebase.firebaseio.com');
$scope.orders = [];
angularFire(ref, $scope, 'orders');

$scope.currentOrder = orderService;

$scope.submitOrder = function() {
  $scope.orders.push($scope.currentOrder);
};

Once orders are pushed into the array, properties like orders[0].customer_name work, but methods like orders[0].value() don't.

It seems reasonable that Firebase/Angularfire would only be syncing JSON, but is there an approach that would allow me to keep order-related logic included with the order object, i.e without having to write $scope.getOrderValue(orders[0])?

2 Answers 2

1

There isn't a great way to do exactly what you want, since according to the Firebase FAQ:

At a low-level, we support basically the same data types as JSON: Strings, Numbers, Booleans, and Objects (which in turn contain Strings, Numbers, Booleans, and more Objects).

Which means you can store data but not functions. It seems like a clean way to accomplish the same thing would be to store the latest order value as a property of your order object, and have a method as part of your orderService that updates it whenever menu items are added or removed. Alternatively, do what you suggested and have a getOrderValue somewhere, but it probably still makes sense to put that in a service.

Sign up to request clarification or add additional context in comments.

2 Comments

If you really do want to do what you proposed, though, you could use the Function constructor (i.e. new Function(orders[0].value)()). Just make sure no one you don't trust is able to modify the value attribute on your objects (e.g. to run a malicious function).
Yeah that is a great point, regardless of how the value is calculated or displayed the user's "version" of the order's value shouldn't be the ultimate authority on the order's true value since it can be manipulated client-side.
0

I actually had the same issue. I wanted to add a method to my firebase object. After looking in the latest angularfire docs I found that $extend can do just that I didn't test it yet, but I think this is the way to go about it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.