diff --git a/docs/class_properties.md b/docs/class_properties.md index 987e918..0c57a1c 100644 --- a/docs/class_properties.md +++ b/docs/class_properties.md @@ -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" }) diff --git a/docs/instance_properties.md b/docs/instance_properties.md index 82b020e..427fe83 100644 --- a/docs/instance_properties.md +++ b/docs/instance_properties.md @@ -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. diff --git a/src/model.js b/src/model.js index c631628..c0db8d6 100644 --- a/src/model.js +++ b/src/model.js @@ -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. diff --git a/test/tests/model.js b/test/tests/model.js index 01fd9e2..fc5cda4 100644 --- a/test/tests/model.js +++ b/test/tests/model.js @@ -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) +})