(hoofbeats) Fixes some anonymous closures and gets scanning working.
[profile/ivi/cowhide.git] / examples / hoofbeats / javascripts / library.js
1 /* vi: set et sw=4 ts=4 si: */
2 (function(win, $) {
3     var library = function() {
4         // For readability:
5         this.initialized = false;
6
7         this.fetchCount = 100;
8         this.fetchOffset = 0;
9         this.mediaItems = [];
10
11         this.initialize = function() {
12             if (this.initialized)
13                 return;
14
15             if (win.tizen === undefined) {
16                 throw Error("You need the Tizen web API  to run Hoofbeats.");
17             }
18
19             this.audioTypeFilter = new tizen.AttributeFilter(
20                 "type", "EXACTLY", "AUDIO");
21             this.videoTypeFilter = new tizen.AttributeFilter(
22                 "type", "EXACTLY", "VIDEO");
23             this.typeFilter = new tizen.CompositeFilter(
24                 "UNION", [this.audioTypeFilter, this.videoTypeFilter]);
25         };
26
27         this.scan = function() {
28             this.deferred = new $.Deferred();
29             this.initialize()
30
31             this.mediaItems = [];
32             this.fetchOffset = 0;
33
34             tizen.content.find(
35                 this.findCB.bind(this),
36                 this.errorCB.bind(this),
37                 null,
38                 this.typeFilter,
39                 null,
40                 this.fetchCount,
41                 this.fetchOffset);
42
43             return this.deferred.promise();
44         };
45
46         this.errorCB = function(error) {
47             console.log("Error: " + error.name);
48             this.deferred.reject();
49             throw new Error(error.name);
50         };
51
52         this.findCB = function(items) {
53             var self = this;
54
55             items.forEach(function(item, index, items) {
56                 self.mediaItems.push(item);
57                 win.MusicBrainz.getArtist(item.artists[0]).done(function(data) {
58                     console.log(data);
59                 });
60             });
61
62             if (items.length == this.fetchCount) {
63                 // There *might* be more items.
64                 this.fetchOffset += this.fetchCount;
65                 tizen.content.find(
66                     this.findCB.bind(this),
67                     this.errorCB.bind(this),
68                     null,
69                     this.typeFilter,
70                     null,
71                     this.fetchCount,
72                     this.fetchOffset);
73             } else {
74                 self.deferred.resolve();
75             }
76         };
77     };
78
79     library.prototype = {
80         set initialized(value) {this._initialized = value; },
81         get initialized() { return this._initialized; }
82     };
83
84     win.HoofbeatsLibrary = library;
85 }(window, jQuery));