I’m trying to use JavaScript prototypes together with jQuery’s .data() function. My code looks like this:
el = this.element;
el.data("state", {
someValue: null,
anotherValue: function() {
this._val = 0;
}
});
el.data("state").anotherValue.prototype.getValue = function() {
return this._val;
}
el.data("state").anotherValue.prototype.setValue = function(val) {
if (val === Infinity || val < 1) {
this._val = 1;
} else {
this._val = val;
}
}
console.log(el.data("state").anotherValue.getValue());
This doesn’t seem work and I’m just curious to know why?
The result I get when I run this code is:
Uncaught TypeError: Object function () {
this._val = 0;
} has no method 'getValue'
I’m working on a jQuery plugin based on the widget factory and I want to build a manageable state machine inside this plugin – a central place where I can store and access the current state of the plugin. One of the reasons I want to try this is that I want to be able to monitor if certain values change and trigger other things when they do. I need to store the data using the .data() function since it has to be tied to the element. Otherwise strange things happen when you get several instances of the plugin on the same page.
Prototype doesn’t seem to be the way to go here. Instead I’m going to try using setters and getters. I’m not 100% sure about browser compatibility but when the example above is rewritten, the code looks like this:
If you run this code you get the following output (in Google Chrome):
When implemented in this way I can run checks and make things happen when the value of a variable is changed or accessed. Please remember that this is preliminary code – I haven’t had time to run it in several browsers on several platforms. Reading this blog post it seems like there’s a browser compatibility issue with IE8.