geddy / model

Datastore-agnostic ORM in JavaScript
265 stars 55 forks source link

Intercepting beforeRemove or remove events #227

Open ivanseidel opened 10 years ago

ivanseidel commented 10 years ago

My model looks like this:

var Photo = function () {

    // Url to photo (Hosted in Cloudinary)
    this.property('publicId', 'string');

    this.afterCreate = function (){
        console.log('AFTER CREATE', this);
        this.on('beforeRemove', function (model, values) {

            console.log('DELETING', values, this);
            // Check if image is uploaded. If so, remove from cloudinary
            if(values.publicId){
            console.log('DELETING', values);
                geddy.cloudinary.api.delete_resources([values.publicId]);
            }
        });
    }
};

It should be listening for beforeRemove events, but it isn't... The max I get, is the afterCreate callback.

Have tried this before, but without succeeding (inside the model):

this.beforeRemove = function (){
   ...
};

Is there anything in the docs explaining this?

Thanks

mde commented 10 years ago

This might be counter-intuitive but "beforeRemove" is a static event emitted by the constructor (the model-definition), and the afterCreate method is on the instances themselves. So inside your afterCreate method, "this" points to the instances.

You can try creating a listener on the constructor itself like this:

geddy.model.Photo.on('beforeRemove', function () { // Do stuff });
ivanseidel commented 10 years ago

I found out the problem...

The EventEmitter is only injected to the model after the geddy.model.register('Photo', Photo);

Placing the Photo.on('beforeRemove', cb) inside the photo.js Model file, must be done AFTER registering it...

(I wanted the callbacks inside the model file)

Thanks!

mde commented 10 years ago

Glad you were able to figure it out!

ivanseidel commented 9 years ago

@mde , there is a problem that I'm facing right now... the Event is emited with just the ID, not the object itself, and the 'this' context is binded to the model constructor, not the item itself.

Because of that, I'm not able to do async stuff, because i don't have the model properties...

Just found a bug?

mde commented 9 years ago

The 'beforeRemove' might be better implemented as an instance method, yes. Let's reopen and reexamine.

ivanseidel commented 9 years ago

In my mind, it should follow the same patter as before[Something], witch is: calling the event handler with a parameter that is the model itself.

The problem with that, is that it won't be compatible with older versions (since the current one callsback with the Id only).

So, we have two options that I can think about:

What do you think?