シンプルなプラグインを作成しようとしていますが、プラグインの状態をどのように管理するかという問題に直面しました。
(function ($) {
// Static things for plugin goes here
var uiHtml = "<div class='gaw-box'>" +
"</div>";
var methods = {
init: function (options) {
return this.each(function () {
// Create UI
$(this).html(uiHtml);
if (options) {
var defaults = {
name:"N/A"
};
var opt = $.extend(defaults, options);
$(this).find(".gaw-name").html(opt.name);
}
// Visual Events attach
var uiobj = $(this).find(".gaw-box");
$(uiobj).mouseenter(function () {
if (!this.isSelected) {
$(this).css('border', '1px solid red');
}
});
$(uiobj).mouseleave(function () {
if (!this.isSelected) {
$(this).css('border', '1px solid black');
}
});
$(uiobj).click(function () {
this.isSelected = !this.isSelected;
if (this.isSelected) {
$(this).css('border', '3px solid red');
}
else {
$(this).css('border', '1px solid black');
}
});
});
},
getIsSelected: function (options) {
return this.isSelected; // ALWAYS FALSE
},
destroy: function () { }
};
$.fn.gateaway = function (method) {
var plugin = this;
plugin.isSelected = false;
if (methods[method])
{
return methods[method].apply(plugin, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(plugin, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.pluginName');
}
};
})(jQuery);
私が達成しようとしているのは、たとえば選択されているかどうかにかかわらず、プラグイン (オブジェクト) の状態を保存することです。プラグインを次のように呼び出しています
$("#gate").gateaway('getIsSelected')
結果は常にfalseです...問題が「この」スコープにあること、クライアントで開発するのはこれが初めてであり、今日それを完了する必要がある2番目の問題であることを知っています:-)各プラグインの状態を保存できるようにプラグインを整理する場所や方法を教えてください:-)