我在查看Jamie Talbot's technique for OOP in jQuery。我試圖理解這種邏輯時非常明白這一點在大多數情況下,但我越來越略輸:jQuery OOP技術混淆
result = $(result);
var template = result[0];
if (template)
{
for (var i in template)
{
if (typeof (template[i]) == 'function')
{
result[i] = function()
{
this.each(function()
{
this[i]();
});
};
}
}
}
我明白到if (typeof (template[i]) == 'function')
塊,該代碼是看每個公共方法這是在插件中聲明的,但在此之後,它讓我感到厭煩。
有沒有什麼機會有人可以一步一步通過這個?
這是Jamie的原始代碼。
(function($) {
$.fn.encapsulatedPlugin = function(plugin, definition, objects, options) {
var result = [];
objects.each(function() {
var element = $(this);
if (!element.data(plugin)) {
// Initialise
var instance = new definition(this, options);
// Store the new functions in a validation data object.
element.data(plugin, instance);
}
result.push(element.data(plugin));
});
// We now have a set of plugin instances.
result = $(result);
// Take the public functions from the definition and make them available across the set.
var template = result[0];
if (template) {
for (var i in template) {
if (typeof (template[i]) == 'function') {
result[i] = function() {
this.each(function() {
this[i]();
});
};
}
}
}
// Finally mix-in a convenient reference back to the objects, to allow for chaining.
result.$ = objects;
return result;
};
})(jQuery);
查看majelbstoat的答案 - 考慮用工作代碼和適當的鏈接更新問題。乾杯。 – 2011-03-21 00:17:24