向一个jQuery/DOM元素添加一个函数

Adding a function to one jQuery/DOM element

本文关键字:一个 添加 函数 元素 jQuery DOM      更新时间:2024-06-27

我正在编写一个实例化地图的插件。然后,地图将提供移动到地球上另一个地方的功能。

脚本使地图变得很好。然而,我不能将函数"钉"在元素上,让另一个插件在回调中使用。

以下是我尝试过的方法;在插件中:

(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)!
  }
};

问题

如果可能的话,我该如何向map jQuery或DOM元素添加函数?如果没有,我该如何提供这种功能?

更重要的是,我这样把事情分开是不是走对了路?我是一个Javascript的新手,这些任务通常是如何在保持组件分离的情况下完成的?

虽然这是我尝试的,但更普遍地说,我在维护可链接性的同时,很难从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/

您可以使用.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);