Reputation: 1065
I'm trying to use the Javascript module pattern for the first time to organize my code. I understand the how "this" works here but cannot figure out how $(this) works. For example, the code below, $(this).addClass('video-active'); in "chooseVideo" function, I want to apply addClass only for the clicked element. But it does not work. Could anybody give me some advice? Thank you!
;(function() {
'use strict';
if (typeof window.jQuery !== 'function') {
return;
}
var $ = jQuery;
var video = {
init: function() {
this.cacheDom();
this.bindEvents();
this.render();
},
cacheDom: function() {
this.$el = $('#videoWrap');
this.$button = this.$el.find('.video');
},
render: function() {
},
bindEvents: function() {
this.$button.bind('click', this.chooseVideo.bind(this));
},
chooseVideo: function(e) {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
this.$button.removeClass('video-active');
$(this).addClass('video-active');
}
};
video.init();
})();
Upvotes: 0
Views: 96
Reputation: 207557
when you use bind, you are changing the context of this
So you will need to use the event object to get what was clicked.
chooseVideo: function(e) {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
this.$button.removeClass('video-active');
$(e.target).addClass('video-active');
Upvotes: 2