Let’s say I wanted to have this API for an example to do app:
var db = new Database('db-name'); // DB connection
var todo = new Todo(db); // New "Todo" and pass it the DB ref
// I want this API:
todo.model.create('do this', function (data) {
console.log(data);
});
I have it setup currently like:
function Todo (storage) {
this.storage = storage;
};
Todo.prototype.model = {
create: function (task, callback) {
// The problem is "this" is Todo.model
// I want the "super", or Todo so I can do:
this.storage.save(task, callback);
}
}
So, if you see the comment, the problem is that “this” inside of model.create is obviously referencing Todo.model, but I need it to grab the “super“.
Best I could think of was:
Todo.prototype.model = function () {
var self = this;
return {
create: function (task, callback) {
// The problem is "this" is Todo.model
// I want the "super", or Todo so I can do:
self.storage.save(task, callback);
}
}
}
But both of these aren’t great. The biggest problem is that I don’t want to have all my methods on model inside of a single object (1st example) or function (2nd). I want to be able to take them out from inside of the model def. Secondly, I’d like to have the todo.model.create API.
Is there a design pattern to achieve this?
You can’t use the prototype pattern for
todo.modelas you’ve written it becausemodelis a property oftodo.I think you need:
a new
Modelobject, on which you can use the prototype model.in the
Todoconstructor, create aModelobject. Ideally, use a read-only “getter” function to allow that model object to be accessed, but not overwritten.