diff --git a/assets/js/application.js b/assets/js/application.js index 41f9f02..19b3132 100644 --- a/assets/js/application.js +++ b/assets/js/application.js @@ -11,7 +11,7 @@ $(document).ready(function() { status: status }), - events: new EventSource('/api/stream'), + events: new Events(queueSongs, status), queue: new Queue('#queue', { queueSongs: queueSongs, @@ -19,17 +19,6 @@ $(document).ready(function() { }) }; - mpdClient.events.onmessage = function(e) { - newStatus = JSON.parse(e.data); - status.attr(newStatus); - } - - status.bind('change', function(event, attr, how, newVal, oldVal) { - if (attr == 'song') { - mpdClient.queueSongs.updatePlaying(oldVal, newVal); - } - }); - }); }); diff --git a/assets/js/constructs/events.js b/assets/js/constructs/events.js new file mode 100644 index 0000000..f40f0c3 --- /dev/null +++ b/assets/js/constructs/events.js @@ -0,0 +1,27 @@ +var Events = can.Construct.extend({ + + init: function(queue, status) { + this.events = new EventSource('/api/stream') + + self = this + + this.events.onmessage = function(e) { + response = JSON.parse(e.data); + switch (response.type) { + case 'status': + status.attr(response.data); + break; + case 'queue': + queue.replace(response.data); + break; + } + } + + status.bind('change', function(event, attr, how, newVal, oldVal) { + if (attr == 'song') { + queue.updatePlaying(oldVal, newVal); + } + }); + }, + +}); diff --git a/assets/js/mpd-client.js b/assets/js/mpd-client.js index 086f396..bc5bc44 100644 --- a/assets/js/mpd-client.js +++ b/assets/js/mpd-client.js @@ -4,5 +4,6 @@ //= require_tree ./models/ //= require_tree ./controls/ +//= require_tree ./constructs/ //= require ./router.js //= require ./application.js diff --git a/mpd_client.rb b/mpd_client.rb index 7919581..14090c2 100644 --- a/mpd_client.rb +++ b/mpd_client.rb @@ -28,12 +28,18 @@ class MPDClient < Sinatra::Base end def self.send_status - status = JSON MPDConnection.status - settings.connections.each { |out| out << "data: #{status}\n\n" } + response = JSON({ type: 'status', data: MPDConnection.status }) + settings.connections.each { |out| out << "data: #{response}\n\n" } + end + + def self.send_queue + response = JSON({ type: 'queue', data: Song.queue.map(&:to_h) }) + settings.connections.each { |out| out << "data: #{response}\n\n" } end MPDConnection.mpd.on(:song) { |song| send_status } MPDConnection.mpd.on(:state) { |state| send_status } + MPDConnection.mpd.on(:playlist) { |playlist| send_queue } namespace '/api' do