【问题标题】:Referencing Settings Object from Init function in jquery从 jquery 中的 Init 函数引用设置对象
【发布时间】:2014-10-03 08:13:53
【问题描述】:

我正在尝试了解 jQuery 插件以及如何在其他函数中引用对象。所以,我有这个:

(function($) {

  var methods = {
    init: function (options) {
      return this.each(function () {
        var defaults  = {
         var1 : 'variable1',
         var2 : 'variable2'
        };
        this.settings = $.extend(defaults,options);
      });
    },
    add: function () {
      // Access settings object here...how??
      alert(this.settings.var1); ????
    }
  };

  jQuery.fn.pluginName = function (method) {
    if (methods[method]) {
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
      return methods.init.apply(this,arguments);
    } else {
      console.error('Method '+method+' does not exist in plugin. Plugin aborted.');
    }
  };

}(jQuery));

所以,我的问题是,一旦我初始化了插件,当调用 'add' 函数时,如何引用 'add' 函数中的设置对象?

非常感谢您的帮助。

【问题讨论】:

  • 如何调用add()函数?

标签: javascript jquery


【解决方案1】:

问题是this的上下文值。

(function($) {

  var methods = {
    init: function(options) {
      return this.each(function() {
        var defaults = {
          var1: 'variable1',
          var2: 'variable2'
        };
        //here this is the dom object not the wrapping jQuery object
        this.settings = $.extend(defaults, options);
      });
    },
    add: function() {
      //here this is the jQuery object

      return this.each(function() {
        //here this is again the dom object
        console.log(this.settings.var1);
      })
    }
  };

  jQuery.fn.pluginName = function(method) {
    if (methods[method]) {
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
      return methods.init.apply(this, arguments);
    } else {
      console.error('Method ' + method + ' does not exist in plugin. Plugin aborted.');
    }
  };

}(jQuery));

$('div').pluginName({
  var1: 'x'
});
$('div').pluginName('add')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

我建议使用数据 api 而不是直接将设置对象附加到 dom 元素引用


我用于插件的一个基本样板是

(function($) {

  function PluginName(el, settings) {
    //your initialization code goes here
    this.$el = $(el);
    this.settings = $.extend({}, jQuery.fn.pluginName.defaults, settings);
  }
  PluginName.prototype.add = function() {
    console.log('add', this, arguments);
  }
  PluginName.prototype.result = function() {
    console.log('result', this, arguments);
    return 'result'
  }
  PluginName.prototype._add = function() {
    console.log('not called');
  }

  jQuery.fn.pluginName = function(method) {
    var result, args = arguments;
    this.each(function() {
      var $this = $(this),
        data = $this.data('pluginName');
      if (data) {
        if (/^[^_]/.test(method) && typeof data[method] == 'function') {
          result = data[method].apply(data, Array.prototype.slice.call(args, 1));
          if (result !== undefined) {
            return false;
          }
        } else {
          throw new Error('Unable to find the method ' + method);
        }
      } else if (typeof method == 'object') {
        data = new PluginName(this, method);
        $this.data('pluginName', data);
      } else {
        throw new Error('Illegal arguments passed');
      }
    })

    return result === undefined ? this : result;

  };


  jQuery.fn.pluginName.defaults = {
    var1: 'variable1',
    var2: 'variable2'
  };
}(jQuery));

$('div').pluginName({
  var1: 'x'
});
try {
  $('div').pluginName('add', 3, 5)
} catch (e) {
  console.log(e);
}
try {
  $('div').pluginName('add2', 3, 5)
} catch (e) {
  console.log(e);
}
try {
  $('div').pluginName('_add', 3, 5)
} catch (e) {
  console.log(e);
}
try {
  var x = $('div').pluginName('result', 3, 5);
  console.log(x)
} catch (e) {
  console.log(e);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div></div>
<div></div>

【讨论】:

  • 谢谢 Arun,这确实很有帮助。
  • 只是跟进说你的样板工作完美,谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-10-13
  • 2015-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-17
  • 1970-01-01
  • 2012-03-01
相关资源
最近更新 更多