gpt4 book ai didi

javascript - 向我澄清这个javascript模式

转载 作者:搜寻专家 更新时间:2023-11-01 04:57:38 24 4
gpt4 key购买 nike

我对如何实现 JavaScript 模式感兴趣,例如,在 jQuery UI 对话框中:

$.dialog('mydialod').dialog('close');

也就是说,在我以 jQuery 兼容的方式创建构造函数后,我不知道如何引用它。

编辑

只是澄清一下:对我来说真正晦涩的是我如何才能拥有某个地方

$('#mydlg').dialog();

然后其他地方

 $('#mydlg').dialog("somecommand");

即使在完全不同的地方似乎也指向原始实例。我认为,它与此 ( jquery.ui.widgets.js ) 有某种关系,

// create selector for plugin
$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
return !!$.data( elem, fullName );
};

但实际上我对 javascript/jquery 太陌生了,无法了解正在发生的事情。

最佳答案

我不确定 jQuery UI 是如何做到的(您必须查看源代码),但这里有一种方法可以做到这一点 https://gist.github.com/elclanrs/5668357

使用这种方法的优点是您可以将所有方法保密,而不是通过使用闭包在原型(prototype)中;在这种情况下是模块模式。

编辑: 好吧,明白了。这就是我让它工作的方式。我称之为“高级 jQuery 样板”。我将这些方法添加到原型(prototype)中,我认为将它们放在外面并没有什么不同,并且可以更容易地在使用 this.method() 的方法中调用方法。 :

(function($) {

var _pluginName = 'myplugin'
, _defaults = {

};

function Plugin(el, options) {
this.opts = $.extend({}, _defaults, options);
this.el = el;
this._init();
}

Plugin.prototype = {
_init: function() {
return this;
},

method: function(str) {
console.log(str);
return this;
}
};

Plugin.prototype[_pluginName] = function(method) {
if (!method) return this._init();
try { return this[method].apply(this, [].slice.call(arguments, 1)); }
catch(e) {} finally { return this; }
};

$.fn[_pluginName] = function() {
var args = arguments;

return this.each(function() {
var instance = $.data(this, 'plugin_'+ _pluginName);

if (typeof args[0] == 'object') {
return $.data(this, 'plugin_'+ _pluginName, new Plugin(this, args[0]));
}
return instance[_pluginName].apply(instance, args);
});
};

}(jQuery));

现在我有两个 div:

<div></div>
<div id="mydiv"></div>

我可以像这样使用插件:

$('div').dialog({ n: 69 }); // initialize both divs

console.log($('#mydiv').dialog('method', 'hello world'));
//=^ prints "hello world" and returns instance

console.log($('#mydiv').data('plugin_dialog').opts.n); //=> 69

它基本上将插件的实例存储在 data 中能够恢复选项,因为此信息已附加到元素。它类似于 jQuery Boilerplate 的方式。有效。

关于javascript - 向我澄清这个javascript模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16805999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com