Sharing settings across methods in namespaced jQuery plugin

后端 未结 2 1695
囚心锁ツ
囚心锁ツ 2021-02-06 05:14

I\'m writing a plugin and following the jQuery documentation\'s recommended practice http://docs.jquery.com/Plugins/Authoring when it comes to namespacing and multiple methods.

2条回答
  •  半阙折子戏
    2021-02-06 05:52

    I didn't look at your plugin template, but I wanted to share this jQuery plugin formatting... it adds a reverse reference to the DOM object in jQuery's stored data. This makes it very easy to access the plugin functions and/or variables even from outside of the plugin closure.

    Here is a post describing the plugin structure in more detail.

    So to access a function inside the plugin, you simply use the data object:

    $('a').data('myplugin').function_name();
    

    or even get a variable from the plugin settings

    var height = $('a').data('myplugin').options.height;
    

    But to answer your question, to make your options available to other functions inside the closure, just define the option variable outside of the init function:

    (function( $ ){
            var options, methods = {
                init: function(customSettings) {
                    options = {
                        debug: true
                    }
    

提交回复
热议问题