So I have repeatedly run into this situation: I write a module patterned object, but am unable to invoke one function from within another (prototyped) function.
;(function($,window,documnet,undefined) {
var id,
_defaults = { };
var MyObject = function(element,options) {
this.el = element;
this.opt = $.extend({},_defaults,options);
this.init(); // works fine
};
MyObject.prototype.init = function() {
var self = this;
self.id = localStorage.getItem('myobject_id');
if( self.id !== null ) {
$('#myobject_id').val(self.id);
}
};
MyObject.prototype.fetch = function() {
var self = this;
var data = {
action: 'program_fetch',
program_idx: $('#program_idx').val()
};
// assume session is valid and has a uri in opt.callback
$.post( session.opt.callback, data ).complete(function(r){
var prog = JSON.parse(r.responseText).program;
self.id = prog.id;
$('#myobject_id').val( self.id ); // this works
self.display(); // this does not work
});
}; /* fetch */
MyObject.prototype.display = function() {
var self = this;
$('#myobject_id').val( self.id );
}; /* display */
$.fn.MyObject = function(options) {
return this.each(function(){
if(!$.data(this,'plugin_MyObject')) {
$.data(this,'plugin_MyObject', new MyObject(options));
}
});
};
window.myobject = new MyObject();
})(jQuery,window,document);
From what I understand, the fetch function ought to be setting the value of the window-attached instance of MyObject, so that when the display() function is called, it has a value to place into the HTML input field, identified by #myobject_id.
What actually seems to happen is there is a race condition during which the value assigned to self.id is viable, but leaving the scope of the .complete(..) callback the value of MyObject.id is no longer valid.
How ought I be invoking these things to achieve persistence in the instance data within my object ?
MyObject.prototype.display('$myobject_id' instead of '#myobject_id')?window.myobject = new MyObject();line if you're only ever instantiatingMyObject's through the jQuery plugin pattern.var self = this;insode of aneach...