0

I have a few scenarios in my application where I need to manipulate the data before it is saved.

I have a CakePHP background so this I would normally do in a Model's beforeSave method.

Is there anything equivalent that I can do in my models in geddy?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
timstermatic
  • 1,710
  • 14
  • 32

1 Answers1

1

Check out the Model events.

Both the base model 'constructors,' and model instances are EventEmitters. The emit events during the create/update/remove lifecycle of model instances. In all cases, the plain-named event is fired after the event in question, and the 'before'-prefixed event, of course happens before.

The 'constructor' for a model emits the following events:

  • beforeCreate
  • create
  • beforeValidate
  • validate
  • beforeUpdateProperties
  • updateProperties
  • beforeSave (new instances, single and bulk)
  • save (new instances, single and bulk)
  • beforeUpdate (existing single instances, bulk updates)
  • update (existing single instances, bulk updates)
  • beforeRemove remove

For example:

var MyModel = function () { ... };

MyModel = geddy.model.register('MyModel', MyModel);

MyModel.on('beforeSave', function(data){
   console.log(data);
})
JAM
  • 6,045
  • 1
  • 32
  • 48
  • Not sure if I am implementing this correctly in my model as it results in User.on('beforeSave', function(){ ^ TypeError: Object function () { this.defineProperties({ email: {type: 'string'}, password: {type: 'string'} }); } has no method 'on' – timstermatic May 16 '13 at 19:24
  • @wiseguysonly Updated my answer. I'm not sure tho, how to get the item being saved - so inside the `beforeSave` event try logging either `this` or `arguments` to see where the `item` you want to manipulate is. Let me know of your progress :) – JAM May 16 '13 at 19:29
  • Thank you that worked. I edited your answer to add the data argument to the anonymous function. With this I can then do data.password etc – timstermatic May 16 '13 at 19:58