jQueryPlugin: query Gist

之前看完30 Days to Learn jQuery後一直想寫個比較完整的jQuery Plugin,最近寫了個自娛娛人的練習,主要用來查詢自己的Gist,查詢關鍵字的部分是對Gist檔名模糊查詢,使用範例:Query Gist 因為用了window.btoa,所以只支援IE10以上的版本。如果真的很介意,坊間有很多替代的加密方式,像是Base64

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
(function ($, window, document, undefined) {
    var Gist = {
        init: function (options, target) {
            var self = this;
            $.extend($.fn.queryGist.options, options);

            self.API_URL = 'https://api.github.com/gists';
            self.$target = $(target);
            self.username = $.fn.queryGist.options.username;
            self.password = $.fn.queryGist.options.password;
            self.search = $.fn.queryGist.options.search.trim().replace(/\s+/, ' ');
            self.fetch().done(function (results) {
                self.list(results);
                self.display();
            }).fail(function(jqXHR, textStatus, errorThrown) {
                alert('Request failed: ' + errorThrown + '\r\n請檢查帳號密碼是否正確!');
            });
        },
        fetch: function () {
            return $.ajax({
                url: this.API_URL,
                headers: { Authorization: 'Basic ' + btoa(this.username + ':' + this.password) }
            });
        },
        list: function (results) {
            var file, regs, i;
            results = results.map(function (gist) {
                file = Object.keys(gist.files)[0];
                return gist.files[file];
            });
            if (!!this.search) {
                regs = this.search.split(' ');
                results = results.filter(function (file) {
                    for (i = 0; i < regs.length; i++) {
                        if (new RegExp(regs[i], 'i').test(file.filename)) {
                            return true;
                        }
                    }
                    return false;
                });
            }
            this.gists = results;
        },
        display: function () {
            var self = this;
            self.$target.html('');
            $(self.gists).each(function (idx, gist) {
                $('<a/>', {
                    href: gist.raw_url,
                    target: '_blank',
                    text: gist.filename
                }).appendTo(self.$target);
                self.$target.append('<br>');
            });
        }
    };

    $.fn.queryGist = function(options) {
        return this.each(function() {
            var gist = Object.create(Gist);
            gist.init(options, this);
        });
    };

    $.fn.queryGist.options = {
        username: null,
        password: null,
        search: null
    };

})(jQuery, window, document);