forked from TapirGo/jquery-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery-tapir.js
81 lines (69 loc) · 2.1 KB
/
jquery-tapir.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
(function($){
var el;
var settings = {};
var methods = {
init: function(options) {
el = this;
settings = {
token: false,
query_param: 'query',
};
if (options) {
$.extend(settings, options);
}
if (!settings.token || settings.query_param == '') {
return this;
}
// Get the query value from the url parsing, or from the argument passed in the method.
var query = paramValue(settings.query_param);
if (settings.query) {
query = settings.query;
}
// Call tapir API and display the result.
$.getJSON(
createUrl(settings.token, query),
function(data) {
displayResult(el, data, settings.complete)
}
);
return this;
}
};
// The function that display the result of the search
function displayResult(el, data, complete) {
// Call the complete callback if needed.
if(complete) {
complete();
}
// The result
el.empty();
$.each(data, function(key, val) {
el.append('<div class="result"><h3><a href="' + val.link + '">'
+ val.title + '</a></h3><p>'
+ val.summary + '</p></div>');
});
};
// The function that create the URL that makes the request to the Tapir API.
function createUrl(token, query) {
return 'http://tapirgo.com/api/1/search.json?token='
+ token
+ '&query='
+ query
+ '&callback=?';
};
// Extract the param value from the URL.
function paramValue(query_param) {
var results = new RegExp('[\\?&]' + query_param + '=([^&#]*)').exec(window.location.href);
return results ? results[1] : false;
};
// Extend jQuery to include the new 'tapir' function.
$.fn.tapir = function(method) {
if (methods[method]) {
return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || ! method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.tapir');
}
};
})( jQuery );