0

私は自分のjavascriptプラグイン、コード(bootstrapのツールチッププラグインから取得して少し変更した)を一般化したかった:

!function ($) {

   "use strict"; // jshint ;_;

   var Conversation = function (element, options) {
      this.init('conversation', element, options);
   };

   // PROTOTYPE DEFINITIONS

   Conversation.prototype = {

      constructor: Conversation,

      init: function (type, element, options) {

         this.type = type;
         this.$element = $(element);
         this.options = this.getOptions(options);
         var $that = $(this);


         this.$element.find('[data-toggle]').on('click', /*HERE*/);

      },

      getOptions: function (options) {
         return $.extend({}, $.fn[this.type].defaults, options, this.$element.data());
      },

      starConversation: function(e){

          console.log('starConversation called!');
      },

      selectConversation: function(e, arg){

         console.log('selectConversation called!');

      },

      selectAllConversations: function(e){
         console.log('selectConversation called!');
      }

   };


   $.fn.conversation = function ( option ) {
      return this.each(function () {
         var $this = $(this)
            , data = $this.data('conversation')
            , options = typeof option == 'object' && option;
         if (!data) $this.data('conversation', (data = new Conversation(this, options)));
         if (typeof option == 'string') data[option]()
      })
   };

   $.fn.conversation.Constructor = Conversation;

   $.fn.conversation.defaults = {
      selectAllButtonSel: '#selectAll'
   };


}(window.jQuery);

問題は、「データトグルを持つすべての要素は、データトグル属性と同じ名前の関数を呼び出す必要がある」というように生成したかったことです。

通常は、

this.$element.find('[data-toggle]').on('click', $.proxy(this['starConversation'], this));

動作します。しかし、クリックされた要素のdata-toggle属性に到達できるかどうか疑問に思いますthis['starConversation']。私もこれを試しました:

$.proxy($that[$(this).data('toggle')], $that);

しかし、$that変数はどういうわけかstarConversation関数変数を持っていません。$.proxy関数内で(または関数のために)スコープが変更されていますon()か?ここでプラグインパターンを壊したくありません。出来ますか?

4

1 に答える 1

0

誰かが[data-toggle]属性を持つ要素をクリックすると、 の値と同じ名前の関数が呼び出されると思います[data-toggle]

考えられる解決策:

this.$element.find('[data-toggle]').on('click', function(event) {
  var methodName = $(this).data('toggle');
  $that[methodName](event);
});
于 2013-03-12T16:17:48.230 に答える