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...
Here is a working version: http://jsfiddle.net/JAAulde/QK35D/3/
Watch this answer for updates as I explain my modifications.
Edits:
#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).var
declaration from in front ofoptions = $.extend( defaults, options );
as it was unneeded and there was risk of wiping what had been passed into the plugin on execution.parseUsername
function to stop adding a space in front of usernames in the username URLs