开发者

Jquery plugin re-inits when method is called

开发者 https://www.devze.com 2023-04-08 19:23 出处:网络
This is my first stab at trying to create a JQuery plugin, so I apologize for my noobbery. My issue is that I believe the plugin is re-initializing when I try to call a public method.It\'s a simple pl

This is my first stab at trying to create a JQuery plugin, so I apologize for my noobbery. My issue is that I believe the plugin is re-initializing when I try to call a public method. It's a simple plugin that creates a div and fills it with tiles, the method .reveal() should remove the tiles.

Plugin declaration:

(function($){

$.fn.extend({

    //pass the options variable to the function
    boxAnimate: function(options) {


        //Set the default values, use comma to separate the settings, example:
        var defaults = {
    bgColor: '#000000',
            padding: 20,
            height: $(this).height(),
    width: $(this).width(),
    tileRows:25,
    tileHeight:$(this).height()/25,
    tileCols:25,
    tileWidth:$(this).width()/25,
    speed: 500
        }

        var options =  $.extend(defaults, options);

    this.reveal = function(){
    var lastTile = $('.backDropTile:last').attr('id');
    var pos1 = lastTile.indexOf("_");
    var pos2 = lastTile.lastIndexOf("_");
    var lCol = parseInt(lastTile.substr(pos2+1));
    var lRow = parseInt(lastTile.substr(pos1+1,(pos2-pos1)-1));
    alert(lCol+' '+lRow+' #bdTile_'+lRow+'_'+lCol);
    for(lRow;lRow>=0;lRow--){
         //Iterate by col:
         for(lCol;lCol>=0;lCol--){
        $('#bdTile_'+lRow+'_'+lCol).animate({
            opacity: 0
            }, 100, function() {
            $('#bdTile_'+lRow+'_'+lCol).remove();
        });
         }
     }
     alert(lCol+' '+lRow);
    }

        return this.each(function(index) {
            var o = options;
    //Create background:
    $(this).prepend('<div id="backDrop" style="color:white;position:absolute;z-index:998;background-color:'+o.bgColor+';height:'+o.height+'px;width:'+o.width+'px;"></div>');
             //create boxes:
     //First iterate by row:

     for(var iRow=0;iRow<o.tileRows;iRow++){
         //Iterate by col:
         for(var iCol=0;iCol<o.tileCols;iCol++){
         $('#backDrop').append('<span class="backDropTile" id="bdTile_'+iRow+'_'+iCol+'" style="z-index:998;float:left;background-color:green;height:'+o.tileHeight+'px;width:'+o.tileWidth+'px;"></span>');
         }
     }

        });
    }
});

})(jQuery);

Usage:

    $(document).ready(function() {
        $('#book').boxAnimate();
        $('#clickme').click(function() {
            $('#book').boxAnimate().reveal();
        });
    });

So I pretty much know what my problem is, but I'm not familiar enough w开发者_Go百科ith creating jQuery plugins to fix it. It's seems like the more I read, the more confused I become as it appears to be many ways to achieve this.


I like to separate my plug-ins into four sections.

1: $.fn implementation that iterates the jQuery element collection and attaches the plug-in.

2: The plug-in "constructor" or init.

3: The plug-in default options

4: The plug-in instance methods or implementation.

Here's how I would have structured your plug-in. I think this is more comprehensible than what you've provided.

(function($){

// constructor or init task
var boxAnimate = function(el, options) {
    this.element = $(el);
    this.options = options;

    if (this.options.height == 'auto') this.options.height = this.element.height();
    if (this.options.width == 'auto') this.options.width= this.element.width();
    if (this.options.tileHeight == 'auto') this.options.tileHeight = this.options.height/25;
    if (this.options.tileWidth == 'auto') this.options.tileWidth = this.options.width/25;

    //Create background:
    this.element.prepend('<div id="backDrop" style="color:white;position:absolute;z-index:998;background-color:'+this.options.bgColor+';height:'+this.options.height+'px;width:'+this.options.width+'px;"></div>');

    //create boxes:
    for(var iRow=0;iRow<this.options.tileRows;iRow++){
        for(var iCol=0;iCol<this.options.tileCols;iCol++){
             $('#backDrop').append('<span class="backDropTile" id="bdTile_'+iRow+'_'+iCol+'" style="z-index:998;float:left;background-color:green;height:'+this.options.tileHeight+'px;width:'+this.options.tileWidth+'px;"></span>');
        }
    }
}

// default options
boxAnimate.defaults = {
    bgColor: '#000000',
    padding: 20,
    height: 'auto',
    width: 'auto',
    tileRows:25,
    tileHeight: 'auto',
    tileCols:25,
    tileWidth: 'auto',
    speed: 500
};

// instance methods
boxAnimate.prototype = {
    reveal: function() {
        var lastTile = $('.backDropTile:last').attr('id');
        var pos1 = lastTile.indexOf("_");
        var pos2 = lastTile.lastIndexOf("_");
        var lCol = parseInt(lastTile.substr(pos2+1));
        var lRow = parseInt(lastTile.substr(pos1+1,(pos2-pos1)-1));

        for(var row=lRow;row>=0;row--) {
            for(var col=lCol;col>=0;col--) {
                $('#bdTile_'+row+'_'+col).animate({
                    opacity: 0
                }, 1000, function() {
                    $('#bdTile_'+row+'_'+col).remove();
                });
             }
         }
    }      
}

// $.fn registration
$.fn.boxAnimate = function(options) {
    return this.each(function() {
        var el = $(this);
        var o = $.extend({}, boxAnimate.defaults, options)
        if (!el.data('boxAnimate'))
            el.data('boxAnimate', new boxAnimate(el, o));
    });
}
})(jQuery);


    $('#book').boxAnimate(); 
    $('#clickme').click(function(e) {
        $('#book').data('boxAnimate').reveal();
        e.preventDefault();
    });


When you assign a method inside the plugin "constructor" like you do here:

this.reveal = function(){}

you are assigning it as a static method of the jQuery.prototype.boxAnimate object. That means you can call it on the object that will be returned from the constructor:

$('#element').boxAnimate().reveal();

or:

var instance = $('#element').boxAnimate();
instance.reveal();

If you wish to place it inside the $.data object instead (personally recommended), you can do like this instead (inside the this.each loop):

$.data(this, 'boxAnimate', {
    reveal: function() {
        // some code
    }
});

Example: http://jsfiddle.net/AyffZ/


First, read this tutorial: http://docs.jquery.com/Plugins/Authoring

Second, your problem is certainly the usage:

$(document).ready(function() {
    $('#book').boxAnimate(); // First Init
    $('#clickme').click(function() {
        $('#book')
            .boxAnimate() // Second Init
            .reveal();
    });
});

The tutorial I linked explains multiple ways to include methods on plugins. You can also use the jQuery UI widget factory, which provides hooks for including methods.

0

精彩评论

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

关注公众号