cordova-tutorial icon indicating copy to clipboard operation
cordova-tutorial copied to clipboard

Wrong usage of this in event listeners

Open slavede opened this issue 10 years ago • 0 comments

Parts with referencing this are completely wrong imo... you have:

navigator.camera.getPicture(
 function(imgData) {
  $('.media-object', this.$el).attr('src', "data:image/jpeg;base64,"+imgData);
 },
 function() {
   alert('Error taking picture', 'Error');
  },
 options);

  return false;
 };

and trying to reference this.$el. When this method is called, this isn't top element where EmployeeView is instantiated, but reference to clicked button. (this works by accident since you have classes for other buttons which would then show this image).

tbh, second part in in jQuery selector (this.$el) is not needed.

Your query always return 8 media-objects (since there are so many of them on screen) and you are changing src of each of them.

What you should do is this:

  1. on beginning of initialization store this into var that:
var EmployeeView = function(employee) {

var that;
this.initialize = function() {
    that = this;
    this.$el = $('<div/>');
    this.$el.on('click', '.add-location-btn', this.addLocation);
    this.$el.on('click', '.add-contact-btn', this.addToContacts);
    this.$el.on('click', '.change-pic-btn', this.changePicture);
};

2). When searching for element to change src do this:

$('.media-object.emp-pic', that.$el).attr('src', "data:image/jpeg;base64,"+imgData);

this way for sure you'll only get one element

slavede avatar Jan 25 '15 16:01 slavede