Skip to content
eyy edited this page Jul 7, 2013 · 1 revision

new witch.Model([data, collection])

A Model is just a simple wrapper around a Javascript object (data), that allows easy sync with the server, and a base class for your own models, with whichever methods or structure you may need.

var user = new witch.Model({ name: 'Helga Bootickler' });
user._url = '/api/users/';
user.save();

As you see and guess, for server communication Model._url must be provided. The above is the silliest way to do so. If you inherit your class from Model, it makes much more sense:

var User = witch.inherit(witch.Model, {
    _url: '/api/users/'
});
var user = new User({ name: 'Verruca Newtroaster' });
user.save();

Another way is by setting the url in the model's associated Collection.

REST Methods

Return promises, so you can model.save().done(cb) them.

fetch([data])

Fetch, and update, the model from the server, at _url/_id. data is attached as querystring.

save()

If _id is set, send a PUT request to _url/_id, otherwise send a POST request to _url.

delete()

Set this._destroyed to true. Collections listen to this and remove the model from their list. If _id is set, send a DELETE request to _url/_id, and only than do the above.

saveAs()

Save the data as a new model (at the associated collection), and clean this from the data. Useful for binding the model to an "Add New" forms:

<form data-on-submit="tsk:saveAs">
    <input type="text" data-value="tsk.text">
    <button type="submit" class="btn">Add task</button>
</form>
<script>
    var tasks = new witch.Collection,
        tsk = new witch.Model({}, col);
    rivets.bind($('form'), { tsk: tsk });
</script>

Other Methods

update(data)

_parse() the data and update the model with it. Called by the associated controller, when it gets new data (e.g. from Controller.fetch()).

_parse(data)

Defaultly, _parse() just returns the data. But you can override it if you need to do something with the data before putting it in the model. Called from within the constructor, update(), save() (parsing the returned data), and fetch().

_clean()

Clean the model's data. Called from within saveAs() and delete().

_callback(data)

A private function that gets called after fetch() and save(). The only difference between this and update() is that here, if the model suddenly gets aמ _id (usually after save()), it gets registered at the associated controller's byId hash.

toJSON()

Return only the model's data, without properties starting with an underscore.