日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

jquery插件開發(fā)范例

 quasiceo 2012-11-23
原文地址:http://www./2007/10/a-plugin-development-pattern
Claim only a single name in the jQuery namespace
This implies a single-plugin script. If your script contains multiple plugins, or complementary plugins (like $.fn.doSomething() and $.fn.undoSomething()) then you'll claim multiple names are required. But in general when authoring a plugin, strive to use only a single name to hold all of its implementation details.
這是一個單一插件的腳本。如果你的腳本中包含多個插件,或者互逆的插件,那么你需要聲明多個函數(shù)名字。但是,通常當我們編寫一個插件時,力求僅使用一個名字來包含它的所有內(nèi)容。
In our example plugin we will claim the name "hilight".
我們的示例插件命名為“hilight”
PLAIN TEXT
JavaScript:
// plugin definition
$.fn.hilight = function() {
  // Our plugin implementation code goes here.
};
And our plugin can be invoked like this:
我們的插件通過這樣被調(diào)用:
PLAIN TEXT
JavaScript:
$('#myDiv').hilight();
But what if we need to break up our implementation into more than one function? There are many reasons to do so: the design may require it; it may result in a simpler or more readable implementation; and it may yield better OO semantics.
但是如果我們需要分解我們的實現(xiàn)代碼為多個函數(shù)該怎么辦?有很多原因:設(shè)計上的需要;這樣做更容易或更易讀的實現(xiàn);而且這樣更符合面向?qū)ο蟆?
It's really quite trivial to break up the implementation into multiple functions without adding noise to the namespace. We do this by recognizing, and taking advantage of, the fact that functions are first-class objects in JavaScript. Like any other object, functions can be assigned properties. Since we have already claimed the "hilight" name in the jQuery prototype object, any other properties or functions that we need to expose can be declared as properties on our "hilight" function. More on this later.
這真是一個麻煩事,把功能實現(xiàn)分解成多個函數(shù)而不增加多余的命名空間。出于認識到和利用函數(shù)是javascript中最基本的類對象,我們可以這樣做。就像其他對象一樣,函數(shù)可以被指定為屬性。因此我們已經(jīng)聲明“hilight”為jQuery的屬性對象,任何其他的屬性或者函數(shù)我們需要暴露出來的,都可以在"hilight" 函數(shù)中被聲明屬性。稍后繼續(xù)。

Accept an options argument to control plugin behavior
Let's add support to our hilight plugin for specifying the foreground and background colors to use. We should allow options like these to be passed as an options object to the plugin function. For example:
讓我們?yōu)槲覀兊牟寮砑庸δ苤付ㄇ熬吧捅尘吧墓δ?。我們也許會讓選項像一個options對象傳遞給插件函數(shù)。例如:
PLAIN TEXT
JavaScript:
// plugin definition
$.fn.hilight = function(options) {
  var defaults = {
    foreground: 'red',
    background: 'yellow'
  };
  // Extend our default options with those provided.
  var opts = $.extend(defaults, options);
  // Our plugin implementation code goes here.
};
Now our plugin can be invoked like this:
我們的插件可以這樣被調(diào)用:
PLAIN TEXT
JavaScript:
$('#myDiv').hilight({
  foreground: 'blue'
});

Provide public access to default plugin settings
An improvement we can, and should, make to the code above is to expose the default plugin settings. This is important because it makes it very easy for plugin users to override/customize the plugin with minimal code. And this is where we begin to take advantage of the function object.
我們應(yīng)該對上面代碼的一種改進是暴露插件的默認設(shè)置。這對于讓插件的使用者更容易用較少的代碼覆蓋和修改插件。接下來我們開始利用函數(shù)對象。
PLAIN TEXT
JavaScript:
// plugin definition
$.fn.hilight = function(options) {
  // Extend our default options with those provided.
  // Note that the first arg to extend is an empty object -
  // this is to keep from overriding our "defaults" object.
  var opts = $.extend({}, $.fn.hilight.defaults, options);
  // Our plugin implementation code goes here.
};
// plugin defaults - added as a property on our plugin function
$.fn.hilight.defaults = {
  foreground: 'red',
  background: 'yellow'
};
Now users can include a line like this in their scripts:
現(xiàn)在使用者可以包含像這樣的一行在他們的腳本里:
PLAIN TEXT
JavaScript:
// this need only be called once and does not
// have to be called from within a 'ready' block
$.fn.hilight.defaults.foreground = 'blue';
And now we can call the plugin method like this and it will use a blue foreground color:
接下來我們可以像這樣使用插件的方法,結(jié)果它設(shè)置藍色的前景色:
PLAIN TEXT
JavaScript:
$('#myDiv').hilight();
As you can see, we've allowed the user to write a single line of code to alter the default foreground color of the plugin. And users can still selectively override this new default value when they want:
如你所見,我們允許使用者寫一行代碼在插件的默認前景色。而且使用者仍然在需要的時候可以有選擇的覆蓋這些新的默認值:
PLAIN TEXT
JavaScript:
// override plugin default foreground color
$.fn.hilight.defaults.foreground = 'blue';
// ...
// invoke plugin using new defaults
$('.hilightDiv').hilight();
// ...
// override default by passing options to plugin method
$('#green').hilight({
  foreground: 'green'
});

Provide public access to secondary functions as applicable
This item goes hand-in-hand with the previous item and is an interesting way to extend your plugin (and to let others extend your plugin). For example, the implementation of our plugin may define a function called "format" which formats the hilight text. Our plugin may now look like this, with the default implementation of the format method defined below the hilight function.
這段將會一步一步對前面那段代碼通過有意思的方法擴展你的插件(同時讓其他人擴展你的插件)。例如,我們插件的實現(xiàn)里面可以定義一個名叫"format"的函數(shù)來格式化高亮文本。我們的插件現(xiàn)在看起來像這樣,默認的format方法的實現(xiàn)部分在hiligth函數(shù)下面。
PLAIN TEXT
JavaScript:
// plugin definition
$.fn.hilight = function(options) {
  // iterate and reformat each matched element
  return this.each(function() {
    var $this = $(this);
    // ...
    var markup = $this.html();
    // call our format function
    markup = $.fn.hilight.format(markup);
    $this.html(markup);
  });
};
// define our format function
$.fn.hilight.format = function(txt) {
return '<strong>' + txt + '</strong>';
};
We could have just as easily supported another property on the options object that allowed a callback function to be provided to override the default formatting. That's another excellent way to support customization of your plugin. The technique shown here takes this a step further by actually exposing the format function so that it can be redefined. With this technique it would be possible for others to ship their own custom overrides of your pluging, in other words, it means others can write plugins for your plugin.
我們很容易的支持options對象中的其他的屬性通過允許一個回調(diào)函數(shù)來覆蓋默認的設(shè)置。 這是另外一個出色的方法來修改你的插件。這里展示的技巧是進一步有效的暴露format函數(shù)進而讓他能被重新定義。通過這技巧,是其他人能夠傳遞他們自己設(shè)置來覆蓋你的插件,換句話說,這樣其他人也能夠為你的插件寫插件。
Considering the trivial example plugin we're building in this article, you may be wondering when this would ever be useful. One real-world example is the Cycle Plugin. The Cycle Plugin is a slideshow plugin which supports a number of built-in transition effects scroll, slide, fade, etc. But realistically, there is no way to define every single type of effect that one might wish to apply to a slide transition. And that's where this type of extensibility is useful. The Cycle Plugin exposes a "transitions" object to which users can add their own custom transition definitions. It's defined in the plugin like this:
考慮到這個篇文章中我們建立的無用的插件,你也許想知道究竟什么時候這些會有用。一個真實的例子是Cycle插件.這個Cycle插件是一個滑動顯示插件,他能支持許多內(nèi)部變換作用到滾動,滑動,漸變消失等。但是實際上,沒有辦法定義也許會應(yīng)用到滑動變化上每種類型的效果。那是這種擴展性有用的地方。Cycle插件對使用者暴露"transitions"對象,使他們添加自己變換定義。插件中定義就像這樣:
PLAIN TEXT
JavaScript:
$.fn.cycle.transitions = {
// ...
};
This technique makes it possible for others to define and ship transition definitions that plug-in to the Cycle Plugin.
這個技巧使其他人能定義和傳遞變換設(shè)置到Cycle插件。

Keep private functions private
The technique of exposing part of your plugin to be overridden can be very powerful. But you need to think carefully about what parts of your implementation to expose. Once it's exposed, you need to keep in mind that any changes to the calling arguments or semantics may break backward compatibility. As a general rule, if you're not sure whether to expose a particular function, then you probably shouldn't.
這種技巧暴露你插件一部分來被覆蓋是非常強大的。但是你需要仔細思考你實現(xiàn)中暴露的部分。一但被暴露,你需要在頭腦中保持任何對于參數(shù)或者語義的改動也許會破壞向后的兼容性。一個通理是,如果你不能肯定是否暴露特定的函數(shù),那么你也許不需要那樣做。
So how then do we define more functions without cluttering the namespace and without exposing the implementation? This is a job for closures. To demonstrate, we'll add another function to our plugin called "debug". The debug function will log the number of selected elements to the Firebug console. To create a closure, we wrap the entire plugin definition in a function (as detailed in the jQuery Authoring Guidelines).
那么我們怎么定義更多的函數(shù)而不攪亂命名空間也不暴露實現(xiàn)呢?這就是閉包的功能。為了演示,我們將會添加另外一個“debug”函數(shù)到我們的插件中。這個debug函數(shù)將為輸出被選中的元素格式到firebug控制臺。為了創(chuàng)建一個閉包,我們將包裝整個插件定義在一個函數(shù)中。
PLAIN TEXT
JavaScript:
// create closure
(function($) {
  // plugin definition
  $.fn.hilight = function(options) {
    debug(this);
    // ...
  };
  // private function for debugging
  function debug($obj) {
    if (window.console && window.console.log)
      window.console.log('hilight selection count: ' + $obj.size());
  };
//  ...
// end of closure
})(jQuery);
Our "debug" method cannot be accessed from outside of the closure and thus is private to our implementation.
我們的“debug”方法不能從外部閉包進入,因此對于我們的實現(xiàn)是私有的。

Support the Metadata Plugin
Depending on the type of plugin you're writing, adding support for the Metadata Plugin can make it even more powerful. Personally, I love the Metadata Plugin because it lets you use unobtrusive markup to override plugin options (which is particularly useful when creating demos and examples). And supporting it is very simple! Update: This bit was optimized per suggestion in the comments.
在你正在寫的插件的基礎(chǔ)上,添加對Metadata插件的支持能使他更強大。個人來說,我喜歡這個Metadata插件,因為它讓你使用不多的"markup”覆蓋插件的選項(這非常有用當創(chuàng)建例子時)。而且支持它非常簡單。更新:注釋中有一點優(yōu)化建議。
PLAIN TEXT
JavaScript:
// plugin definition
$.fn.hilight = function(options) {
  // ...
  // build main options before element iteration
  var opts = $.extend({}, $.fn.hilight.defaults, options);
  return this.each(function() {
    var $this = $(this);
    // build element specific options
    var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
    //...
This changed line does a couple of things:
這些變動行做了一些事情:
it tests to see if the Metadata Plugin is installed
它是測試Metadata插件是否被安裝
if it is installed, it extends our options object with the extracted metadata.
如果它被安裝了,它能擴展我們的options對象通過抽取元數(shù)據(jù)
This line is added as the last argument to jQuery.extend so it will override any other option settings. Now we can drive behavior from the markup if we choose:
這行作為最后一個參數(shù)添加到JQuery.extend,那么它將會覆蓋任何其它選項設(shè)置?,F(xiàn)在我們能從"markup”處驅(qū)動行為,如果我們選擇了“markup”:
<!--  markup  -->
<div class="hilight { background: 'red', foreground: 'white' }">
  Have a nice day!
</div>
<div class="hilight { foreground: 'orange' }">
  Have a nice day!
</div>
<div class="hilight { background: 'green' }">
  Have a nice day!
</div>

And now we can hilight each of these divs uniquely using a single line of script:
現(xiàn)在我們能高亮哪些div僅使用一行腳本:
PLAIN TEXT
JavaScript:
$('.hilight').hilight();

Putting it All Together
Below is the completed code for our example:
下面使我們的例子完成后的代碼:
PLAIN TEXT
JavaScript:
//
// create closure
//
(function($) {
  //
  // plugin definition
  //
  $.fn.hilight = function(options) {
    debug(this);
    // build main options before element iteration
    var opts = $.extend({}, $.fn.hilight.defaults, options);
    // iterate and reformat each matched element
    return this.each(function() {
      $this = $(this);
      // build element specific options
      var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
      // update element styles
      $this.css({
        backgroundColor: o.background,
        color: o.foreground
      });
      var markup = $this.html();
      // call our format function
      markup = $.fn.hilight.format(markup);
      $this.html(markup);
    });
  };
  //
  // private function for debugging
  //
  function debug($obj) {
    if (window.console && window.console.log)
      window.console.log('hilight selection count: ' + $obj.size());
  };
  //
  // define and expose our format function
  //
  $.fn.hilight.format = function(txt) {
    return '<strong>' + txt + '</strong>';
  };
  //
  // plugin defaults
  //
  $.fn.hilight.defaults = {
    foreground: 'red',
    background: 'yellow'
  };
//
// end of closure
//
})(jQuery);
This design pattern has enabled me to create powerful, consistently crafted plugins. I hope it helps you to do the same.
這段設(shè)計已經(jīng)讓我創(chuàng)建了強大符合規(guī)范的插件。我希望它能讓你也能做到。

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多