繁体   English   中英

将函数添加到一个jQuery / DOM元素

[英]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显示它的实际效果:

http://jsfiddle.net/X8YA8/1/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM