2012-02-01 77 views
1

我創建的jQuery插件:如何創建一個返回另一個對象的jQuery函數?

$.fn.myGrid = function() { 

    return ???; 
} 

我想要的myGrid返回值包括附加功能,讓我可以在下面的方式來使用它;

var grid = $(".myGrid").myGrid(); 
grid.add(); 

我該怎麼做?我如何聲明添加函數?我還有什麼要返回myGrid插件?

我也很高興有這樣的作品;

$.myGrid.add(); 

這可能嗎?

回答

3

一個你可以使用的方法是this;

$.fn.myGrid = function() { 
    var that = this; 

    return { 
     add: function() { 
      that.after('<h2>Here I am, adding something'); // Note `that` rather than `this`. 
     }, 
     remove: function() { 
      that.next().remove(); 
     } 
    }; 
} 

捕捉this變量是很重要的,因爲否則從myGrid()函數的對象,你return上的方法將無法訪問您的調用myGrid() jQuery對象。

請參閱此處的操作代碼; http://jsfiddle.net/HpeS8/

0

通常情況下,寫了一個插件,最好的約定是這樣的:

$.fn.pluginName = function(){ 
    // return the same object to preserve chainability 
    // and also apply the plugin's functionality to all the 
    // dom elements in this jquery collection 
    return this.each(function(i,el){ 
     // do whatever you want with $(el) 
    }); 
}; 

如果你正在寫返回,而不是在某種程度上當前對象(比如像width作品操縱值插件),你應該返回值,而不是當前對象的引用(this):

$.fn.maxWidth = function(){ 
    var max = 0; 
    this.each(function(i,el){ 
     var w = $(el).width(); 
     if(w > max) 
      max = w; 
    }); 
    return max; 
}; 

如果你想給用戶訪問&修改的可能性喲你應該保持鏈接性(我的意思是返回this而不是包含你插件的api的其他對象),並通過jQuery元素的data方法向用戶公開插件的API。
下面是一個例子。讓我們說我們正在製作一個視頻播放器jquery插件。我們希望保持鏈接性,但仍然能夠訪問此插件的核心功能。
做到這一點的正確的方式將是這樣的:

$.fn.videoPlayer = function(){ 
    var api = { 
     play : function(){/*...*/}, 
     pause : function(){/*...*/}, 
     stop : function(){/*...*/} 
    }; 

    return this.each(function(i,el){ 
     $(el).data('videoPlayerApi',api); 
    }); 
}; 

的使用示例這表明我的觀點:

$('video') 
    // initialising the plugin 
    .videoPlayer() 
    // the return value is the original jQuery object, 
    // so we can still call jQuery methods on it 
    .css('opacity',1) 
    // select the first video 
    .eq(0) 
     // access the first video's plugin api 
     .data('videoPlayerApi') 
      // start only the first video 
      .start(); 
0
 (function ($) { 
      var methods = { 
       init: function() { 
        //Initilize 
      }, 
      var add = { 
       //Do something 
      } 
       $.fn.myGrid= function (method) { 
        if (methods[method]) { 
         return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); 
        } 
        else if (typeof method === 'object' || !method) { 
         return methods.init.apply(this, arguments); 
        } 
     else { $.error('Method ' + method + ' does not exist on jQuery.myGrid'); } 
    }; 
})(jQuery); 

這樣調用

var grid = $(".myGrid").myGrid(); 
grid.myGrid("add"); 
相關問題