Skip to content

Commit

Permalink
Transform support when creating models on-the-fly
Browse files Browse the repository at this point in the history
Now when you use reste.createModel, it will add a default transform
(toJSON) — this can be overridden if the model is defined in config and
has a transform function there.
  • Loading branch information
jasonkneen committed Apr 4, 2017
1 parent acc1eb3 commit 5d1cc50
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion reste.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ var main = function() {

// open the url and check if we're overrding with
// a local http based url

if (args.url.indexOf("http") >= 0) {
http.open(args.method, args.url);
} else {
Expand Down Expand Up @@ -354,6 +355,29 @@ var main = function() {

reste.createModel = function(name, attributes) {
var model = new Backbone.Model(attributes);

// if we have a config based transfor for th emodel
// then attach this to the model, or create a default
if (reste.modelConfig && reste.modelConfig[name].transform) {
model.transform = function(model, transform) {
if (transform) {
this.__transform = transform(this);
} else {
this.__transform = reste.modelConfig[name].transform(this);
}
return this.__transform;
};
} else {
model.transform = function(model, transform) {
if (transform) {
this.__transform = transform(this);
} else {
this.__transform = this.toJSON();
}
return this.__transform;
};
}

model._type = name;
return model;
};
Expand Down Expand Up @@ -390,7 +414,7 @@ var main = function() {
} else if (args.transform) {
this.__transform = args.transform(this);
} else {
this.__transform = this.toJSON()
this.__transform = this.toJSON();
}
return this.__transform;
}
Expand Down

0 comments on commit 5d1cc50

Please sign in to comment.