I’m trying to use a “class” (prototypes) on javascript and i’m having a strange “undefined” error.
/**
* Use the camera to take a picture and use it as custom image.
*/
function CameraMedia(imgTag, saveButton){
this.__camera__ = navigator.camera;
this.__imageTag__ = imgTag;
this.__saveButton__ = saveButton;
this.__selectedImage__ = null;
}
/**
* Executes the camera of the device.
* @param {Object} type selects between gallery or camera. Parameters could be "GALLERY" or "CAMERA" ignoring case.
*/
CameraMedia.prototype.run = function(type){
var that = this;
function onDeviceReady(){
var options = {
quality: 50,
allowEdit : true
};
that.__camera__.getPicture(that.__successOperation__, that.__errorOperation__, options);
}
document.addEventListener("deviceready", onDeviceReady, true);
};
/**
* Operation that might be performed in case of success in taking the image.
*/
CameraMedia.prototype.__successOperation__ = function(imageData){
this.__selectedImage__ = imageData;
$(this.__imageTag__).attr("src", imageData);
$(this.__imageTag__).attr("image-changed", true);
$(this.__saveButton__).show();
}
/**
* Operation that might be performed in case of error in taking the image.
*/
CameraMedia.prototype.__errorOperation__ = function(message){
alert(message);
}
The problem is this elements on __successOperation__ doesn’t reference to CameraMedia object.
Thanks.
This is normal. You are passing a function from a object (which is basically a hashmap) to the callback, not the entire object.
To work around this, jQuery has a proxy method (and underscore has a bind method), they go something like this:
If you wish to use vanilla javascript, you can achieve this also (example 3):
JSFiddle: http://jsfiddle.net/PBxFs/