2011-04-02 88 views
3

我想學寫jQuery插件,所以我認爲這將通過把我的功能集成到一個插件,比如更容易爲如果我知道這我明白了:jquery插件:將函數轉換爲插件?

這些都是我的正常功能,

this.delete_uploaded = function(){ 

    $(".delete-uploaded").click(function(){ 

     // remove the popup. 
     $('#popup_result').remove(); 

     // same as: var target_delete = $(this).parent().parent().parent(); 
     var target_delete = $(this).parents('.item-uploaded'); // the item for deletion, such as item held in li 
     var parent_delete = $(this).parents('.items-uploaded'); // the parent that hold delete item, such as ul > li 
     var wrapper_parent = $(this).parents('.upload'); // the wrapper that hold the parent, such as div > ul > li 
     var target_loadin = $(this).parent(); 
     var target_html = $(this).parent().html(); 
     var path_load = $(this).attr('href'); 

     // make a gif loader. 
     target_loadin.html('<img src="'+http_root+rp_image_global+img_loader+'" style="float:none;"/> loading'); 

     // load the delete form. 
     target_loadin.load(path_load, function(){ 

      // when the yes button is triggered. 
      $("input[type=submit][name=yes]").click(function(){ 

       // get the path from attribute of action in the form. 
       var path_post = $(this).parent('form').attr('action'); 
       //alert(path_post); 

       // make a gif loader. 
       target_loadin.html('<div class="ajaxloader"><img src="'+http_root+rp_image_global+img_loader+'" style="float:none;"/> loading</div>'); 

       // post the form. 
       $.post(path_post, $(this).serialize(), function(xml){ 

        // procees the form output. 
        process_delete_uploaded(xml); 
       }); 

       // slide up the deleted target. 
       target_delete.slideUp('fast', function() { 

        // remove its divs completely 
        target_delete.remove(); 
        //alert($('li',parent_delete).length); 

        // count how many items are left behind   
        if($('li',parent_delete).length == 0) 
        { 
         $('.binder-row',wrapper_parent).css({ 
          borderBottom: '0px solid #999', 
          padding: '0px 0px 0px 0px' 
         }); 
        } 

       }); 

       return false; 
      }); 

      // when the no/cancel button is triggered. 
      $("input[type=button][name=no]").click(function(){ 

       // return the html 
       target_loadin.html(target_html); 

       // reload the delete function 
       delete_uploaded(); 

       return false; 
      }); 

     }); 

    return false; 
    }); 
} 

// callback function for proccesing the deleted item. 
this.process_delete_uploaded = function(xml){ 

    // append a popup div. 
    $(document.body).append("<div id=\"popup_result\" class=\"popup\"></div>"); 

    var popup = $('#popup_result'); 
    var width = 400; 
    var top = 220; 
    var scrollTop = $(window).scrollTop(); 
    var scrollLeft = $(window).scrollLeft(); 
    var marginLeft = "-"+ ((scrollLeft + width)/2); 

    popup.css({ 
     top:(scrollTop + top) + "px", 
     left:"50%", 
     marginLeft:marginLeft + "px", 
     width:width + "px", 
     zIndex:"11", 
     display:"none" 
    }); 

    // proccess the result and load the result page and display the result messages on the result page. 
    popup.load(http_root+rp_cms+"result.php", {}, function(){ 

     // loop for any error messages. 
     $("error", xml).each(function(){ 
      var elementid = $(this).attr('elementid'); 
      var message = $(this).attr('message'); 
      $("#"+elementid+"_label").addClass('error'); 
      $("#"+elementid+"_img").css({visibility:'visible'}); 
      $(".result").append("<img src='"+http_root+rp_image_global+"attention.png' /> <b>" + message + "</b> <br />"); 
      popup.fadeIn('slow', function(){  
       closePopup(popup); 
      }); 
     }); 

     // loop for any positive results. 
     $("result", xml).each(function(){ 

      // store the result node. 
      var message = $(this).attr('message'); 
      //alert(message); 

      // append the positive messages in the result class. 
      $(".result").append("<img src='"+http_root+rp_image_global+"info.png' /> <b>" + message + "</b> <br />"); 

      // display the messages by fading them in. 
      popup.fadeIn('fast', function(){ 

       // set the timeout to 1 minute to remove the popup 
       setTimeout(function(){ 
        popup.fadeOut("slow",function(){ 
         popup.remove(); 
        }); 
       },1000);  

       // attach closePopup function. 
       closePopup(popup);  
      }); 

     }); 
    }); 
} 

我想將它轉換成一個插件,這樣我可以像這樣的實例化,

$(".delete-uploaded").delete_uploaded({ 
    target_delete: '.item-uploaded', 
    parent_delete: '.items-uploaded', 
    wrapper_parent:'.upload' 
}) 

等,

$(".delete-listed").delete_uploaded({ 
    target_delete: '.item-listed', 
    parent_delete: '.items-listed', 
    wrapper_parent:'.upload' 
}) 

這可能嗎?

謝謝。

編輯:

我嘗試到目前爲止好...

// You need an anonymous function to wrap around your function to avoid conflict 
(function($){ 

    // Attach this new method to jQuery 
    $.fn.extend({ 

     // This is where you write your plugin's name 
     pluginname: function(options) { 

      //Set the default values, use comma to separate the settings, example: 
      var defaults = { 
       deleteTarget: '.item-listed', 
       deleteParent: '.items-listed', 
       wrapperParent: '.upload', 
      } 

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

      return this.click(function(){ 
       var o = options; 

       var target_delete = $(this).parents(o.deleteTarget); // The item for deletion, such as item held in li 
       var parent_delete = $(this).parents(o.deleteParent); // The parent that hold delete item, such as ul > li 
       var wrapper_parent = $(this).parents(o.wrapperParent); // The wrapper that hold the parent, such as div > ul > li 
       var target_loadin = $(this).parent(); 
       var target_html = $(this).parent().html(); 
       var path_load = $(this).attr('href'); 

       // Make a gif loader. 
       target_loadin.html('<img src="'+http_root+rp_image_global+img_loader+'" style="float:none;"/> loading'); 
       //alert(target_html); 

       // Load the delete form. 
       target_loadin.load(path_load, function(){ 

        // When the yes button is triggered. 
        $("input[type=submit][name=yes]").click(function(){ 

         // Get the path from attribute of action in the form. 
         var path_post = $(this).parent('form').attr('action'); 
         //alert(path_post); 

         // Make a gif loader. 
         target_loadin.html('<div class="ajaxloader"><img src="'+http_root+rp_image_global+img_loader+'" style="float:none;"/> loading</div>'); 

         // Post the form. 
         $.post(path_post, $(this).serialize(), function(xml){ 

          // Procees the form output. 
          process_delete_uploaded(xml); 
         }); 

         // Slide up the deleted target. 
         target_delete.slideUp('fast', function() { 

          // Remove its divs completely 
          target_delete.remove(); 
          //alert($('li',parent_delete).length); 

          // Count how many items are left behind   
          if($('li',parent_delete).length == 0) 
          { 
           $('.binder-row',wrapper_parent).css({ 
            borderBottom: '0px solid #999', 
            padding: '0px 0px 0px 0px' 
           }); 
          } 

         }); 

         return false; 
        }); 
       }); 

       return false; 

      }); 

     } 
    }); 

//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); 

我遵循了here教程。它工作得很好,即使我不明白爲什麼我必須使用jquery.extend()...

回答

3

下面是一個不完整的例子,應該讓你走好人生路:

$.fn.delete_uploaded = function(settings) { 
    /* Define defaults for each of the settings: */ 
    var target_delete = settings.target_delete || '.item-uploaded'; 
    var parent_delete = settings.parent_delete || '.items-uploaded'; 
    var wrapper_parent = settings.wrapper_parent || '.upload'; 

    /* "this" is already a jQuery object: */ 
    this.click(function() { ... }); 
}; 

Here的編寫jQuery插件的文檔。希望有所幫助! jQueryUI source code也很有用。

編輯:您不必使用extend,但根據您的情況使用它可能會更方便。 Here是一個很好的答案,涉及$.fn.extend

+0

非常感謝這個安德魯!我一直在努力 - 看看我上面的編輯。謝謝:-) – laukok 2011-04-02 14:45:20

+0

@lauthiamkok:很高興幫助!你不必使用'.fn.extend',這只是另一種做事的方式。 – 2011-04-02 15:02:16

+0

感謝您的鏈接安德魯! :-) – laukok 2011-04-02 15:12:31