component / model

Minimalistic extensible data models
122 stars 40 forks source link

Added async plugin support #28

Closed matthewmueller closed 9 years ago

matthewmueller commented 11 years ago

This pull request adds asynchronous plugin support to the saving and removing events. I found this useful on the server-side, but I'm sure some people will find it useful on the client-side.

The implementation inspects the function's length (like Mocha) to determine if it's an async plugin or not.

var pwd = require('pwd');

User.use(hash);

/**
 * Hashing Function
 */ 

function hash(User) {
  User.attr('salt')
  User.on('saving', function(user, done) {
    if(!user.isNew()) return done();
    pwd.hash(user.password(), function(err, hash) {
      user.salt(hash);
      done();
    });
  });
}

Definitely open to suggestions, modifications, or ideas.

tj commented 11 years ago

ah yeah I omitted this on the client since preemptive async validations are kinda lame but on the server I agree, not sure I love highjacking the emitter for this, I'll review tonight

matthewmueller commented 11 years ago

yah, I can't really think of a use case for this feature on the client-side off the top of my head. But maybe someone else will have some ideas.

I'm really liking this model implementation and have been retrofitting it to work with mongo (through monk). I think the last step is to get the transport layer abstracted out.

matthewmueller commented 11 years ago

yah, I do agree that the hijacking is a bit of a hack, but it does maintain the API and doesn't introduce anything new, eg:

function hash(User) {
  User.attr('salt')
  User.before('save', fn);
}

The other thing I don't really like is that pet is redundant:

pet.on('saving', function(pet, next) { ... });

Probably should be:

pet.on('saving', function(next) { ... });

Couldn't come up with a clean way of differentiating between the Pet.on('saving') and pet.on('saving') callback signatures.

yields commented 11 years ago

yah, I can't really think of a use case for this feature on the client-side off the top of my head. But maybe someone else will have some ideas.

indexeddb is async.

domachine commented 11 years ago

+1