-3

次のコードがあります。

<script>
jQuery(document).ready(function ($) {
  'use strict';
  var Image_Selector = function () {};

  Image_Selector.prototype.init = function ($wrapper) {
    this.$select_btn = $wrapper.find('.set-image-btn');

    this.$select_btn.click(function (e) {
      console.log(this);    //jquery object
      console.log(e);       //just the event

      // What's the best way to call 'open_image_selector()' here?
    });
  }; // init

  Image_Selector.prototype.open_image_selector = function () {
    console.log (this);
    // do awesome stuff
  };
}); // doc rdy
</script>

関数open_image_selector内で呼び出す最良の方法は何ですか?jquery.click

4

2 に答える 2

1

thisclcik ハンドラー内には、クリックされる DOM 要素があります。

クラスthisを clcik ハンドラーの外にキャッシュして、ハンドラー内で使用できるようにします。$.proxyハンドラーのコンテキストを変更するためにも使用できます

Image_Selector.prototype.init = function ($wrapper) {

     var self=this;
    self.$select_btn = $wrapper.find('.set-image-btn');

    self.$select_btn.click(function (e) {
      console.log(self); /* should log "Image_Selector" object*/
       self.open_image_selector()  

    });
  }; // init
于 2013-03-30T11:06:30.943 に答える
1

使用bind方法

 this.$select_btn.click(function (e) {
    console.log(this);
    console.log(e);
    //Calling `open_image_selector`
    this.open_image_selector()
 }.bind(this)); 

thisクリック リスナーにバインドして、thisその関数内でオブジェクトの現在のインスタンスを参照するようにしImage_Selectorます。

于 2013-03-30T11:19:27.100 に答える