Skip to content

Commit

Permalink
Instance-level property-change events.
Browse files Browse the repository at this point in the history
  • Loading branch information
Dan Dean committed Aug 31, 2012
1 parent b7338a8 commit f0b8097
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 8 deletions.
4 changes: 2 additions & 2 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ TODO
* Data store's should be able to extend their Model API when necessary.
* Fire data-driven events (EventEmitter2)

model.on('change', function(name, value, old) {});
model.on('change:name', function(value, old) {});
model.on('change', function(name, value, old) {});
model.on('change:name', function(value, old) {});
model.on('delete', function(model) {});

* Fire Model-type level data-driven events:
Expand Down
15 changes: 9 additions & 6 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,8 @@ Model.create = function(options) {
return value;
},
set: function(value) {
var oldValue = this.fields[key];

// Note: setting value to undefined resets the property to its default
// value, if configured.
if (value === undefined) {
Expand All @@ -369,13 +371,14 @@ Model.create = function(options) {
return;
}
}

if (setters[key]) {
// Property was configured with a setter -- pass the value through it.
this.fields[key] = setters[key](value);

} else {
this.fields[key] = value;
// If property was configured with a setter -- pass the value through it.
this.fields[key] = setters[key] ? setters[key](value) : value ;
var newValue = this.fields[key];

if (oldValue !== newValue) {
this.emit('change', key, oldValue, newValue);
this.emit('change:' + key, oldValue, newValue);
}
},
enumerable: true,
Expand Down
25 changes: 25 additions & 0 deletions test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,31 @@ describe('Model', function() {
assert.equal(30, model.age);
});

it('should emit events when properties change', function(done) {
var model = new TestModel1();

model.on('change', function(property, old, value) {
assert.equal('username', property);
assert.equal(undefined, old);
assert.equal('radical', value);
done();
});

model.username = 'radical';
});

it('should emit events when a specific property change', function(done) {
var model = new TestModel1();

model.on('change:username', function(old, value) {
assert.equal(undefined, old);
assert.equal('radical', value);
done();
});

model.username = 'radical';
});

it('should serialize models to JSON', function() {
var model = new TestModel1(); // id == 6
var json = model.toJSON();
Expand Down

0 comments on commit f0b8097

Please sign in to comment.