Skip to content

Instantly share code, notes, and snippets.

@PaquitoSoft
Created October 17, 2012 09:44
Show Gist options
  • Save PaquitoSoft/3904714 to your computer and use it in GitHub Desktop.
Save PaquitoSoft/3904714 to your computer and use it in GitHub Desktop.
Geddy base behaviour for controllers
/*
* Geddy JavaScript Web development framework
* Copyright 2112 Matthew Eernisse ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
var Application = function () {
};
Application.prototype.setupController = function (modelName) {
var resourceName = modelName.toLowerCase();
this.respondsWith = ['html', 'json', 'xml', 'js', 'txt'];
this.index = function (req, resp, params) {
var self = this;
geddy.model[modelName].all(function(err, results) {
var atts = {params: params};
atts[resourceName + 's'] = results;
self.respond(atts);
});
};
this.add = function (req, resp, params) {
this.respond({params: params});
};
this.create = function (req, resp, params) {
var self = this,
resource = geddy.model[modelName].create(params);
resource.save(function(err, data) {
if (err) {
params.errors = err;
self.transfer('add');
} else {
self.redirect({controller: self.name});
}
});
};
this.show = function (req, resp, params) {
var self = this;
geddy.model[modelName].load(params.id, function(err, result) {
var atts = {params: params};
atts[resourceName] = result.toObj();
self.respond(atts);
});
};
this.edit = function (req, resp, params) {
var self = this;
geddy.model[modelName].load(params.id, function(err, result) {
var atts = {params: params};
atts[resourceName] = result;
self.respond(atts);
});
};
this.update = function (req, resp, params) {
var self = this;
geddy.model[modelName].load(params.id, function(err, result) {
result.updateAttributes(params);
result.save(function(err, data) {
if (err) {
params.errors = err;
self.transfer('edit');
} else {
self.redirect({controller: self.name});
}
});
});
};
this.destroy = function (req, resp, params) {
var self = this;
geddy.model[modelName].remove(params.id, function(err) {
if (err) {
params.errors = err;
self.transfer('edit');
} else {
self.redirect({controller: self.name});
}
});
};
};
exports.Application = Application;
var Todos = function () {
this.setupController('Todo');
};
exports.Todos = Todos;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment