Skip to content

Commit b2b55a2

Browse files
committed
Emit a "change" or "change:ATTRIBUTE_NAME" event when modifying attributes on an instance.
1 parent 465a7c6 commit b2b55a2

File tree

3 files changed

+36
-10
lines changed

3 files changed

+36
-10
lines changed

src/model_instance_methods.js

+2
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,14 @@ Model.InstanceMethods = {
1515
} else {
1616
this.changes[name] = value;
1717
}
18+
this.trigger("change:" + name, [this])
1819
return this;
1920
} else if (typeof name === "object") {
2021
// Mass-assign attributes.
2122
for (var key in name) {
2223
this.attr(key, name[key]);
2324
}
25+
this.trigger("change", [this])
2426
return this;
2527
} else {
2628
// Changes take precedent over attributes.

test/tests/model_rest_test.js

+3-10
Original file line numberDiff line numberDiff line change
@@ -464,23 +464,16 @@ test("create event", 1, function() {
464464
this.persistence(Model.REST, "/posts")
465465
});
466466

467-
var events = []
468-
469-
// Stub trigger and capture its argument.
470-
Post.prototype.trigger = function(name) {
471-
events.push(name)
472-
}
473-
474467
var server = this.sandbox.useFakeServer()
475468
server.respondWith("POST", "/posts", [200, {
476469
"Content-Type": "application/json"
477470
}, JSON.stringify({ id: 1 })])
478471

479-
new Post().save()
472+
var post = new Post()
473+
post.bind("create", function() { ok(true) })
474+
post.save()
480475

481476
server.respond()
482-
483-
deepEqual(events, ["create"])
484477
});
485478

486479
test("update event", 1, function() {

test/tests/model_test.js

+31
Original file line numberDiff line numberDiff line change
@@ -277,3 +277,34 @@ test("saving a model with an id should add it to the collection if it isn't alre
277277

278278
ok(Post.first() === post)
279279
})
280+
281+
test("change event", 5, function() {
282+
var Post = Model("post")
283+
var post = new Post({ foo: "bar", abc: 123, xyz: 789 })
284+
285+
var events = []
286+
287+
post.bind("change", function(p) {
288+
ok(p === post)
289+
events.push("change")
290+
})
291+
292+
post.bind("change:foo", function(p) {
293+
ok(p === post)
294+
events.push("change:foo")
295+
})
296+
297+
post.bind("change:xyz", function(p) {
298+
ok(p === post)
299+
events.push("change:xyz")
300+
})
301+
302+
post.bind("change:abc", function() {
303+
ok(false)
304+
})
305+
306+
post.attr("foo", "baz")
307+
post.attr({ foo: "bob", xyz: 123 })
308+
309+
same(events, ["change:foo", "change:foo", "change:xyz", "change"])
310+
})

0 commit comments

Comments
 (0)