我想概括我的 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);
问题是我想像“所有具有 data-toggle 的元素都应该调用与它们的 data-toggle 属性一样命名的函数”。
一般,
this.$element.find('[data-toggle]').on('click', $.proxy(this['starConversation'], this));
作品。但我想知道我是否可以在this['starConversation']
. 我也试过这个:
$.proxy($that[$(this).data('toggle')], $that);
然而$that
变量不知何故没有starConversation
函数变量。范围是否在$.proxy
函数内部(或因为on()
函数)发生了变化?我不想在这里打破插件模式。可能吗?