2012-06-27 6 views
0

Я сейчас переписываю плагин jQuery, который будет использоваться в RSS-ридере, который я создаю во время стажировки. Этот плагин использует API каналов Google, чтобы вытащить RSS-канал, отформатированный в формате JSON, и вернуть его разработчику, позволяя им настраивать контроль над тем, как этот канал отображается на веб-странице. Я слежу за официальной страницей jQuery Plugin Authoring в качестве ссылки.Неполадки Написание правильного плагина jQuery

На ссылочной странице примеры кода говорят, что вам нужно добавить свой плагин к прототипу 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 

Что я делаю неправильно?

ответ

5

Вы добавляете к $.fn, если вы хотите, чтобы ваша функция будет доступна на JQuery экземпляров (например, объекты, которые вы получите назад от $("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>

+0

Ooooohhhh, который имеет много смысла. Я пытался изменить поведение стандартного объекта jQuery вместо создания статической функции (из-за отсутствия лучшего термина). Спасибо за ваш ответ и разъяснение! –

+0

@ Зак: Не беспокойтесь, рад, что помог. Лучший, –

1

Смотрите, где я сделал именно то, что автор хочет сделать here! я просто использовал этот шаблон я использую в течение многих лет :

(function($) { 
    if (!$.myExample) { // check your plugin namespace does not already exist 
     $.extend({ // this will allow you to add your plugin to the jQuery lib 
      myExample: function(elm, command, args) { 
       // keep in mind, right here you might want to do a class or data check to determine which direction this call is going 
       // for example, upon init the plugin on an element you may add the plugin name as a class, 
       //  this way, when it's recalled, you can see it alrady has that class and might be calling a command, 
       //   thus make an if statemnt to push the process through 
       return elm.each(function(index){ 
        // do work to each element as its passed through 
        // be sure to use something like 
        // return elm.each(function(e) { dor work }); 
        // as your final statement in order to maintain "chainability" 
       }); 
      } 
     }); 
     $.fn.extend({ // this gives the chainability functionality seen with $ funcs like: $("#eleID").css("color", "red") <--returns original element object 
      myExample: function(command) { 
       return $.myExample($(this), command, Array.prototype.slice.call(arguments, 1)); 
      } 
     }); 
     $.myExample.props = { // Here you can establish specific properties to your plugin, prehaps even make them "Over-writable" 
      key1: "value", 
      key2: "value" 
     }; 
     $.myExample.methods = { // Here you can establish specific methods/functions for your plguin to carry out and maintain your namespace as well 
      key1: function(param) { 
       /* do work */ 
      }, 
      key2: function(param) { 
       /* do work */ 
      } 
     }; 
     // This next part is not seen in many plugins but useful depending on what you're creating 
     $.myExample.init = function(param) { // If you have an initialize method to apply, namespace it in here and calll on initializing your plugin 
      var key = "value", 
       key2 = { 
        subKey: "value" 
       }; 
       /* 
       /run any number of initializing functions here 
       /I prefer to make my param a value that can be a 
       / string with a possible object 
       / the string for holding a base configuration 
       / the object for any change in properties or base values for that config 
       */ 
     }; 
     $.myExample.defaults = { // establish base properties here that can be over-written via .props, but their values should never truly change 
      key1: "value", 
      key2: { 
       prop1: { 
        subKey1: "value", 
        subKey2: "value" 
       }, 
       prop2: { 
        subKey1: "value" 
       } 
      }, 
      key3: function(param) { 

      } 
     }; 
    } 
})(jQuery); 
Смежные вопросы