Trouble Converting jQuery Script to Plugin

2019-06-04 01:58发布

I'm trying to convert a pretty simple script that takes search results from Twitter and outputs it into an unordered list. This is my first time trying to write a plugin and it doesn't seem to be firing all the code when I call it. Script by iteself works fine, this is the code I've written for the plugin:

(function($) {

    $.fn.tweetGet = function(options) {

        var defaults = {

            query: 'from:twitter&rpp=10',
            url: 'http://search.twitter.com/search.json?callback=?&q='
        };

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

        return this.each(function() {

            // Get tweets from user query
            $.getJSON(options.url + options.query, function(data) {

                var tweets = [];

                $.each(data.results, function(i, tweet) {

                    tweets.push('<li>' + tweet.text.parseURL().parseUsername().parseHashtag() + '</li>');
                });

                $('#target').append('<ul>' + tweets.join('') + '</ul>');
            });

            // Parse tweets for URLs and convert to links
            String.prototype.parseURL = function() {
                return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+/g, function(url) {
                    return url.link(url);
                });
            };

            // Parse tweets for twitter usernames and convert to links
            String.prototype.parseUsername = function() {
                return this.replace(/(?:^|\s)@[a-zA-Z0-9_.-]+\b/, function(user) {
                    var username = user.replace("@","")
                    return user.link("http://twitter.com/"+username);
                });
            };

            // Parse tweets for hashtags and convert to links
            String.prototype.parseHashtag = function() {
                return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(hash) {
                    var hashtag = hash.replace("#","%23")
                    return hash.link("http://search.twitter.com/search?q="+hashtag);
                });
            };
        });
    };
})(jQuery);

The function is being called with:

$('#target').tweetGet({query: 'from:twitter&rpp:10'});

Everything outside of return this.each(function() {}; is working fine, but nothing placed within is firing or giving me any errors. All the tutorials I've read seem to use this same basic format but I can't seem to figure out what I'm doing wrong...

1条回答
霸刀☆藐视天下
2楼-- · 2019-06-04 02:26

Here is a working version: http://jsfiddle.net/JAAulde/QK35D/3/

( function( global )
{
    var String, $;

    if( global.jQuery )
    {
        String = global.String;
        $ = window.jQuery;

        String.prototype = $.extend( String.prototype, {
            // Parse tweets for URLs and convert to links
            parseURL: function()
            {
                return this.replace( /[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+/g, function( url )
                {
                    return url.link( url );
                } );
            },
            // Parse tweets for twitter usernames and convert to links
            parseUsername: function()
            {
                return this.replace( /@[a-zA-Z0-9_.-]+\b/g, function( user )
                {
                    return user.link( 'http://twitter.com/' + user.replace( '@', '' ) );
                } );
            },
            // Parse tweets for hashtags and convert to links
            parseHashtag: function()
            {
                return this.replace( /[#]+[A-Za-z0-9-_]+/g, function( hash )
                {
                    return hash.link( 'http://search.twitter.com/search?q=' + hash.replace( '#', '%23' ) );
                } );
            }
        } );

        $.fn.tweetGet = function( options )
        {
            var defaults = {
                query: 'from:twitter&rpp=10',
                url: 'http://search.twitter.com/search.json?callback=?&q='
            };

            options = $.extend( defaults, options );

            return this.each( function()
            {
                var target = this;
                // Get tweets from user query
                $.getJSON( options.url + options.query, function( data )
                {
                    var tweets = [];

                    $.each( data.results, function( i, tweet )
                    {
                        tweets.push( '<li>' + tweet.text.parseURL().parseUsername().parseHashtag() + '</li>' );
                    } );

                    $( target ).append( '<ul>' + tweets.join('') + '</ul>' );
                } );
            } );
        };
    }
}( window ) );

Watch this answer for updates as I explain my modifications.

Edits:

  1. removed all modifications of the string prototype out of the plugin--they should not be there as they are not part of the plugin code, and they would be redefined on every call to the plugin.
  2. removed the #target selector from within the plugin as it specifically targeted an element rather than using the collection against which the plugin had been called (adjusted for scope due to getJSON callback).
  3. removed the var declaration from in front of options = $.extend( defaults, options ); as it was unneeded and there was risk of wiping what had been passed into the plugin on execution.
  4. as an aside, fixed your parseUsername function to stop adding a space in front of usernames in the username URLs
  5. used my preferred syntax for localizing code
查看更多
登录 后发表回答