Skip to content

Commit

Permalink
Add the ability to define a custom initialize instance method that is…
Browse files Browse the repository at this point in the history
… called at the end of the initialization process.
  • Loading branch information
benpickles committed Sep 28, 2010
1 parent ad2c9c0 commit 1ec4c07
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 1 deletion.
2 changes: 1 addition & 1 deletion docs/class_properties.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ Calls [`read()`](#read) on the persistence adapter and adds the returned models

#### `new(attributes)`

Instantiates a model, the supplied attributes get assigned directly to the model's [`attributes`](#attributes).
Instantiates a model, the supplied attributes get assigned directly to the model's [`attributes`](#attributes). Custom initialization behaviour can be added by defining an [`initialize()`](#initialize) instance method.

var fish = new Food({ name: "fish" })

Expand Down
14 changes: 14 additions & 0 deletions docs/instance_properties.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,20 @@ Returns an [`Errors`](#api-errors) object containing information about any faile

Convenience method, equivalent of calling `attr("id")`.

#### `initialize()`

If an `initialize()` instance method is defined on a class it is called at the end of the initialization process.

var User = Model("user", {}, {
initialize: function() {
this.attr("state", "initialized")
}
})
var user = new User()

user.attr("state")
// => "initialized"

#### `merge(object)`

Destructivly merges the given object into the [`attributes`](#attributes) object. Used internally when saving and not really required for everyday use.
Expand Down
1 change: 1 addition & 0 deletions src/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ var Model = function(name, class_methods, instance_methods) {
this.changes = {};
this.errors = new Model.Errors(this);
this.uid = [name, Model.UID.generate()].join("-")
if (jQuery.isFunction(this.initialize)) this.initialize()
};

// Persistence is special, remove it from class_methods.
Expand Down
12 changes: 12 additions & 0 deletions test/tests/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -249,3 +249,15 @@ test("persistence failure", function() {

same(events, [], "should not trigger destroy event if persistence failed");
});

test("#initialize", function() {
var Post = Model("post", {}, {
initialize: function() {
this.initialized = true
}
})

var post = new Post()

ok(post.initialized)
})

0 comments on commit 1ec4c07

Please sign in to comment.