Correct way to wrap dialog in an object?
I want to create an object to manage collections of notes in an application. I create a constructor and on its prototype add edit, save and cancel functions. So
function jNotes() {};
jNotes.prototype = {
doEdit: function(anIndex) { ... },
doSave: function() { ... },
doCancel: function() { ... }
}
I would like to use a JQuery UI Dialog when the user edits a note. So, in the doEdit function I create the dialog with save and cancel buttons that I want to point to the jNotes doSave and doCancel functions. Because 'this' within the dialog constructor will point to the dialog, before constructing the dialog I save 'this' to a var. My code looks like:
doEdit: function(anIndex) {
var j = this;
$(function() {
$("#pnlEditNotes").dialog({
buttons: {" Save ": j.doSave, "Cancel": j.doCancel, },
modal: true,
title: "Notes",
});
});
}
The problem I have is that when the user hits the save button and doSave is called, 'this' in the doSave function refers to the dialog rather than the instance of jNotes that created the dialog. The only way I can see of overcoming this is to create an instance of jNotes, say oNotes, and hardwire the dialog button callback functions to oNotes, e.g.
buttons: {" Save ": oNotes.doSave, "Cancel": oNotes.doCancel, },
This works, but it forces the jNotes to be a singleton with me forcing the name of the instance to be something of my choosing. That doesn't seem right. What is the proper way to embed a dialog into an object so that the dialog can call the proper doSave function in the instance of jNotes that created it?