开发者

How to add accessor method to element via plugin?

开发者 https://www.devze.com 2023-02-27 06:05 出处:网络
I have a plugin that transforms the selected values from a dropdown menu into a concatenated string for use inside a text field.

I have a plugin that transforms the selected values from a dropdown menu into a concatenated string for use inside a text field.

The plugin is called like this:

info = $('select');
info.my_plugin({ /* plugin options */ });

What I would like to do is to add an accessor method on that element (preferably the jQuery collection), such that at a later time, I could call (after the code above):

info.get_values();

Which 开发者_如何学Pythonwould call a private method (defined in the plugin) to return the currently set value for the jQuery element.

How do I modify my plugin to do this? My plugin is currently setup using this pattern:

$.fn.my_plugin = function(options) {};


I suggest using jQuery's .data. Like

$.fn.myPlugin = function (options) {

    var handler = {};

    this.data('myPlugin', handler);

    handler.options = options;

    handler.getValues = function () {
        // return some values
    };

    return this;

};

This way, the API your plugin exposes stays isolated and clean.

Then your users could do

$('select').myPlugin();

// later somewhere else
$('select').data('myPlugin').getValues();

Note: I took this idea long ago from jQuery tools. Don't know if they are still doing this.


You would have to extend the $.fn object with another function, like this:

$.fn.my_plugin = function(options) {

    // ...your plugin code, setting the var "concatenatedDropDownString"

    $.fn.get_values = function(){
        return concatenatedDropDownString;
    };

    return concatenatedDropDownString;
};
0

精彩评论

暂无评论...
验证码 换一张
取 消