无法将jQuery脚本转换为插件 [英] Trouble Converting jQuery Script to Plugin

查看:91
本文介绍了无法将jQuery脚本转换为插件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试转换一个非常简单的脚本,该脚本从Twitter获取搜索结果并将其输出到无序列表中.这是我第一次尝试编写插件,当我调用它时似乎并没有触发所有代码.脚本本身运行良好,这是我为插件编写的代码:

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);

该函数的调用方式为:

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

之外的所有内容都返回this.each(function(){}; )工作正常,但其中没有任何内容引发或给我任何错误.我阅读的所有教程似乎都在使用相同的基本格式,但我似乎无法弄清楚我在做什么错...

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...

推荐答案

以下是有效版本: 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.

  1. 从插件中删除了对字符串原型的所有修改-它们不应该存在,因为它们不是插件代码的一部分,并且每次调用插件时都将重新定义它们.
  2. 从插件中删除了#target选择器,因为它专门针对某个元素,而不是使用针对其调用了该插件的集合(由于getJSON回调而对范围进行了调整).
  3. var声明从options = $.extend( defaults, options );前面删除,因为这是不必要的,并且存在在执行时清除传递给插件的内容的风险.
  4. 顺便说一句,修复了您的parseUsername函数,以停止在用户名URL中的用户名前面添加空格
  5. 使用了我首选的语法来本地化代码
  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

这篇关于无法将jQuery脚本转换为插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆