An extension for cloak.model
that adds the Model::url
method.
var Model = require('cloak.model');
var modelUrl = require('cloak.model.url');
// Enable the model for all models
modelUrl.extendModel(Model);
// Create a new example model
var Person = Model.extend({
initialize: function() {
this._super();
// Define the URL for this model
this.url('/people{/#}');
},
attrs: {
name: ''
}
});
var bob = new Person();
// As this is a brand new model, it has no ID, so calling ::url will return "/people"
bob.url();
// Now, let's give bob an ID ...
bob.id('123');
// Now that an ID is set, the "#" variable will be replaced and the url will be "/people/123"
bob.url();
var Document = Model.extend({
initialize: function() {
this._super();
// Define the URL for this model; This URL is a little more complex
this.url('/people/{owner}/documents{/#}');
},
attrs: {
owner: User
}
});
// Create a new document
var doc = new Document();
// Without the required owner field filled in, this actually gives a bad URL "/people//documents"
doc.url();
// Let's define the owner as bob from the previous example
doc.set('owner', bob);
// Now bob's ID gets put in that spot "/people/123/documents"
doc.url();
// Let's define an ID for the document
doc.id('234');
// Now both values populate like we want "people/123/documents/234"
doc.url();