0
我工作的NodeJS創建一種能夠一次發送圖片到多個顯示器,目前我的代碼有以下語句:的NodeJS合併對象
var $ = require('jQuery');
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app, { log:false });
var fs = require('fs');
var Server = {
server_address : "XXX.XXX.XXX.XXX", // The server address
playing_now : Object // The playlist that are being synced
};
var Client = {
clients : Object
};
app.listen(1337);
console.log("App is running on port 1337...");
function handler(request, response) {
var ip_address = null;
try{ ip_address = request.header('x-forwarded-for'); }
catch(error){ ip_address = request.connection.remoteAddress; }
Client.clients[ip_address] = "X";
fs.readFile(__dirname + '/index.html', function (err, data) {
if (err) {
response.writeHead(500);
return response.end('Error loading index.html');
}
response.writeHead(200);
response.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.on("RequestPlaylist", function(json){
Client.clients[json["Address"]] = json["PlayList"];
if(typeof Server.playing_now[json["PlayList"]] === 'undefined'){
$.ajax({
url : "http://" + Server.server_address + "/buildPlayList.php",
type : "GET",
dataType : "jsonp",
method : "GET",
data : {RemoteIP : json["Address"], Name : json["PlayList"]}
}).done(function(playlistJSON){
console.log("________________________________________");
console.log("Done");
console.log(Server.playing_now);
Server.playing_now[playlistJSON["playName"]] = playlistJSON;
console.log(Server.playing_now);
console.log("________________________________________");
})
}else{
console.log("________________________________________");
console.log("Redirect");
console.log(Server.playing_now);
console.log("________________________________________");
}
});
});
當一個新的客戶端連接,我保存它的IP地址在Client.clients上,當我得到包含圖像的url的json時,我將它存儲在Server.playing_now上。
的問題是,當我輸出Server.playing_now,它包括Client.clients的內容:
Done
{ [Function: Object] 'XXX.XXX.XXX.XXX': 'Default Media' }
{ [Function: Object]
'XXX.XXX.XXX.XXX': 'Default Media',
'Default Media':
{ '1':
{ json: [Object],
duration: '5',
name: 'Slideshow',
type: 'Image',
sync: '1',
callback: 'jQuery17207063492417801172_1377555709748' },
playName: 'Default Media' } }
如果嘗試再次讀取該數據,這是結果:
Redirect
{ [Function: Object]
'105.102.15.234': 'Default Media',
'Default Media':
{ '1':
{ json: [Object],
duration: '5',
name: 'Entrenamiento PL',
type: 'Image',
sync: '1',
callback: 'jQuery17207063492417801172_1377555709748' },
playName: 'Default Media' } }
我的代碼沒有任何合併這兩個對象,如果我註釋掉Client對象,它只返回Server.playing_now的內容。
任何想法可能發生什麼?或者是預期這種行爲?
這做到了,所以當我將它設置爲只對象,它繼承了所有我追加到任何的屬性和方法我基於相同的初始化創建的其他對象?我有一些代碼清理然後....謝謝!你可能只是省了很多麻煩。 – desto
在這種情況下,「對象」是用於創建類型爲Object的新事物的構造函數,並且在範圍內是全局的。所以基本上你正在做的是將屬性分配給代碼中引用它的不同位置的全局變量。 – dc5