您好我正在尝试使用Atmosphere创建一个简单的聊天应用程序。
我的Application1.xml无法使用创建“Socket”的引用
var socket = $.atmosphere;
。
以下是我使用过的代码块。我是气氛中的菜鸟。
application1.xml $(function(){ “使用严格”;
var content = $('#content');
var input = $('#input');
var status = $('#status');
var myName = false;
var author = null;
var logged = false;
var socket = $.atmosphere;
var request = { url: document.location.toString() + 'chat',
contentType : "application/json",
logLevel : 'debug',
transport : 'websocket' ,
trackMessageLength : true,
fallbackTransport: 'long-polling'};
request.onOpen = function(response) {
content.html($('<p>', { text: 'Atmosphere connected using ' + response.transport }));
input.removeAttr('disabled').focus();
status.text('Choose name:');
};
request.onMessage = function (response) {
var message = response.responseBody;
try {
var json = jQuery.parseJSON(message);
} catch (e) {
console.log('This doesn\'t look like a valid JSON: ', message);
return;
}
input.removeAttr('disabled').focus();
if (!logged) {
logged = true;
status.text(myName + ': ').css('color', 'blue');
} else {
var me = json.author == author;
var date = jQuery.now();
addMessage(json.author, json.message, me ? 'blue' : 'black', new Date(date));
}
};
request.onClose = function(response) {
logged = false;
}
request.onError = function(response) {
content.html($('<p>', { text: 'Sorry, but there\'s some problem with your '
+ 'socket or the server is down' }));
};
var subSocket = socket.subscribe(request);
input.keydown(function(e) {
if (e.keyCode === 13) {
var msg = $(this).val();
// First message is always the author's name
if (author == null) {
author = msg;
}
subSocket.push(jQuery.stringifyJSON({ author: author, message: msg }));
$(this).val('');
input.attr('disabled', 'disabled');
if (myName === false) {
myName = msg;
}
}
});
function addMessage(author, message, color, datetime) {
content.append('<p><span style="color:' + color + '">' + author + '</span> @ ' +
+ (datetime.getHours() < 10 ? '0' + datetime.getHours() : datetime.getHours()) + ':'
+ (datetime.getMinutes() < 10 ? '0' + datetime.getMinutes() : datetime.getMinutes())
+ ': ' + message + '</p>');
}
});
atmosphere.js
答案 0 :(得分:0)
这样声明大气变量并不好:
var socket = $.atmosphere;
如果你的bower.json中声明了大气库,并且大气中的所有javascript源都被声明为bower组件,请分配变量氛围,如:
var socket = atmosphere;