$(this) in JavaScript Module Pattern

$(this) in JavaScript Module Pattern

本文关键字:JavaScript Module Pattern in this      更新时间:2023-09-26

我第一次尝试使用Javascript模块模式来组织我的代码。我了解"this"在这里的工作原理,但无法弄清楚 $(this) 是如何工作的。例如,下面的代码,$(this).addClass('video-active');在"选择视频"功能中,我只想对单击的元素应用 addClass。但它不起作用。有人可以给我一些建议吗?谢谢!

;(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();
})();

当你使用bind时,你正在改变this的上下文

因此,您需要使用事件对象来获取单击的内容。

chooseVideo: function(e) {
   e.preventDefault ? e.preventDefault() : e.returnValue = false;
   this.$button.removeClass('video-active');
   $(e.target).addClass('video-active');