0

私は、インターンシップ中に構築している RSS リーダーで使用する jQuery プラグインを書き直しています。このプラグインは、Google の Feed API を使用して JSON 形式の RSS フィードを取得し、開発者に返します。これにより、Web ページでのフィードの表示方法を微調整できます。公式のjQuery Plugin Authoringページを参照としてフォローしています。

リファレンス ページのコード例では、プラグインを jQuery のプロトタイプに追加する必要があることが示されています$.fn。これが私がやったことです:

(function($) {
    "use strict";

    $.fn.rssObj = function(newUrl) {
        var RSSFeed = function(newUrl) {
            /*
             * An object to encapsulate a Google Feed API request.
             */

            this.feedUrl = newUrl;
        };

        RSSFeed.prototype.load = function() {
            var feed = new google.feeds.Feed(this.feedUrl);
            feed.load(function(result) {
                console.log(result);
            });
        };

        return new RSSFeed(newUrl);
    };

})(jQuery);

を実行してこのプラグインを使用しようとする$.rssObj("http://rss.test.com")と、ブラウザで次のエラーが表示されます。

$.rssObj() is not a function

私は何を間違っていますか?

4

2 に答える 2

5

関数をjQueryインスタンス$.fnで使用できるようにする場合はに追加します(たとえば、取得したオブジェクトなど)。オブジェクトから直接関数を使用できるようにする場合は、オブジェクトに直接追加します。$("your selector here")$

それぞれを示す例を次に示します。

// Creating the plugin
(function($) {
  
  // This will be on *instances*
  $.fn.green = function() {
    // `this` is the jQuery instance we were called on
    return this.css("color", "green");
  };
  
  // This will be on the $/jQuery object itself
  $.blue = function(selector) {
    // You don't use `this` here (you could if you want,
    // it will be === $/jQuery, but there's no reason to)
    $(selector).css("color", "blue");
    return this;
  };
  
})(jQuery);

// Usage
jQuery(function($) {
  
  // Make all divs green with a border
  $("div").green().css("border", "1px solid green");
  
  // Make all paragraphs blue
  $.blue("p");
  
});
<div>I'm a div</div>
<p>I'm a paragraph</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

于 2012-06-27T13:56:46.337 に答える