私は自分の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()
か?ここでプラグインパターンを壊したくありません。出来ますか?