[英]Adding a function to one jQuery/DOM element
我正在創作一個實例化地圖的插件。 然后地圖將提供移動到地球上另一個地方的功能。
該腳本使地圖很好。 但是,我不能“修復”元素上的函數,以供回調中的另一個插件使用。
這是我嘗試過的方法; 在插件中:
(function($){
$.fn.mapDo(options){
map = new BlahMap(this.get(0));
this.moveTheMap = function(place){
map.moveItToThat(place);
}; // nope.
}
})(jQuery);
然后,在視圖中:
$(map).mapDo();
$(otherElement).otherControl({
callback: function(place){
$(map).moveTheMap(place); // moveTheMap is not there on $(map)!
}
};
如果可能,如何向地圖jQuery或DOM元素添加函數? 如果沒有,我該如何提供這種功能?
更重要的是,我是否通過這種方式將事情分開? 我有點像Javascript的初學者,這些任務通常是如何在保持組件分開的同時完成的?
雖然這是我對它的抨擊,但更普遍的是,我在保持可鏈接性的同時,努力解決從jQuery插件輸出內容的問題。 在這種情況下,我想要做的是從插件中輸出一個回調,該回調將在執行后期對被調用元素起作用。
您可以使用.data
方法存儲map
。
(function($){
$.fn.mapDo = funciont(options) {
this.data('map', new BlahMap(this.get(0)));
return this;
};
$.fn.moveTheMap = function(place) {
var map = this.data('map');
if (map) {
map.moveItToThat(place);
}
return this;
};
})(jQuery);
插件通常只向jQuery原型添加一個方法,並且對插件的實例的方法調用是使用字符串完成的。
(function($) {
$.fn.mapDo = function(options) {
var args = [].slice.call(arguments, 1); //Get all the arguments starting from 2nd argument as an array
return this.each(function() {
var $this = $(this),
instance = $this.data("map-instance");
if (!instance) {
$this.data("map-instance", (instance = new BlahMap(this, options)));
}
if (typeof options == "string") {
instance[options].apply(instance, args);
}
});
};
})(jQuery);
$(elem).mapDo( "moveTheMap", place ); //This would also instantiate the plugin if it wasn't instantiated
這是jsfiddle顯示它的實際效果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.