In the Bookshelf model provided below, the users password is hashed when the model is saved. However, an issue arises when changing the model.set()
call to a model.save()
, leading to an endless loop of saving and changing.
var User = bookshelf.Model.extend({
tableName: 'users',
hasTimestamps: true,
constructor: function() {
var self = this;
bookshelf.Model.apply(this, arguments);
this.on('saving', function(model) {
if(!model.get('password')) {
return self.hashPassword(model);
}
});
},
hashPassword: function(model) {
bcrypt.genSalt(10, function(error, salt) {
bcrypt.hash(model.attributes.password, salt, function(error, hash) {
model.set({password: hash});
console.log(model.attributes);
});
});
}
});
It is known that Backbone offers a silent: true
option to avoid triggering a change event with save()
, but it is unclear whether or not Bookshelf supports this feature.
What are some ways to save the changes made by model.set()
without encountering a save/changed loop?