将jQuery对象/代码转换为插件

turn jQuery object/code into a plugin

本文关键字:转换 插件 代码 jQuery 对象      更新时间:2023-09-26

所以我已经阅读了一些教程,我仍然困惑如何把我的特定标签系统变成一个可用的插件。

我用一堆函数声明了下面的对象:

var Tags = {};
Tags.Class = function() {
  ...
};

然后声明原型:

Tags.TaggingForm = new Tags.Class();
// Only takes text input fields for now!
Tags.TaggingForm.prototype = {
    initialize: function(tag_field){
       ...
    },
    hideInputField: function() {
      ...
    },

然后我有了实际的函数调用使用那个对象:

Tags.make_tagging_input = function (id) {
var
 tagger = new Tags.TaggingForm(id);
...
 }

我只是想知道如何把它变成一个插件:目前我这样称呼它:

window.g_gloab_var = Tags.make_tagging_input("#id");

这个框架一直被建议,但我不确定如何应用它:

//You need an anonymous function to wrap around your function to avoid conflict

(函数(美元){

//Attach this new method to jQuery
$.fn.extend({ 
    //This is where you write your plugin's name
    tags_input: function() {
        //Iterate over the current set of matched elements
        return this.each(function() {
            //code to be inserted here
        });
        }
    });
//pass jQuery to the function, 
//So that we will able to use any valid Javascript variable name 
//to replace "$" SIGN. But, we'll stick to $ (I like dollar sign: ) )       
})(jQuery);

现在没有时间深入讨论这个,但是我最喜欢的插件创建样板是Stefan Gabos的

很好的评论,很容易理解。希望这对你有所帮助。当我有更多时间的时候我会再来看看,但希望这对现在有帮助。

你可以使用你的原始代码,并有一个插件,像这样:

(function($) {
// your original code here
$.fn.extend({ 
    tags_input: function(options) {
        //Iterate over the current set of matched elements
        // that we would call via $(selector).tags_input(options);
        // e.g. $('.tags_input').tags_input({a: true, b: "some string"});
        return this.each(function() {
            // call your plugin here,
            // options can be an object of parameters to the plugin
            // using your code and calling it on "this"
            // e.g. Tags.make_tagging_input("#" + this.id);
        });
        }
    });
})(jQuery);