我正在嘗試使用es6來創建聊天室連接類。我正在使用rabbitmq/STOMP將交換數據推送給訂戶。我使用的代碼已經以es5風格工作,但我對交換名稱進行了硬編碼。我使用的WebPack /通天transpile該代碼回來叫chat.bundle.js
文件ES5但是當我運行:實例化es6類
var chatRoom = new ChatRoom('thisExchange');
控制檯日誌:Uncaught ReferenceError: ChatRoom is not defined
我捆後實例化類ChatRoom
文件被加載(在該文件包的腳本標籤下面)。
我知道大概load()
函數將無法正常工作......我是es6類的新手,不確定如何讓window.load工作,但這是一個單獨的問題。現在我只想通過提供exchangeName
的參數來實例化這個類,然後在這之後繼續處理新的錯誤。
這是我非常寫入器ES6類:
// Use SockJS
Stomp.WebSocketClass = SockJS;
// Connection parameters
var mq_username = "guest",
mq_password = "guest",
mq_vhost = "/",
mq_url = 'http://localhost:15674/stomp',
mq_queue = "/exchange/${this.exchange}";
var output;
var client = Stomp.client(mq_url);
class ChatRoom {
constructor(exchange){
this._exchange=exchange;
}
get exchange(){
return this._exchange;
}
toString() {
return `${this.exchange}`
}
on_connect() {
output.innerHTML += 'Connected to RabbitMQ-Web-Stomp<br />';
console.log(client);
client.subscribe(mq_queue, on_message);
}
// This will be called upon a connection error
on_connect_error() {
output.innerHTML += 'Connection failed!<br />';
}
// This will be called upon arrival of a message
on_message(m) {
console.log('message received');
console.log(m);
output.innerHTML += m.body + '<br />';
}
load(){
return new Promise(function(resolve,reject){
window.onload = () => {
// Fetch output panel
output = document.getElementById("output");
// Connect
client.connect(
self.mq_username,
self.mq_password,
self.on_connect,
self.on_connect_error,
self.mq_vhost
);
}
});
}
}
在我的HTML文件,腳本標籤結構如下:
<script src="static/chat.bundle.js"></script>
<script>var chatRoom=new ChatRoom('[email protected]');</script>
的WebPack成功建立,不抱怨的語法聊天包的es6文件如上所示。
見webpack docs這可能是因爲你的類從未定義。你在「使用嚴格」模式?如果不是這樣,可能與下面的帖子有相同的答案: http://stackoverflow.com/questions/34231445/es6-classes-dont-work-on-chrome-47 –
一些提示:是chat.bundle。 js文件正確創建(沒有任何錯誤)?你什麼時候做'var chatRoom = new ChatRoom('thisExchange');'?檢查你在哪裏訪問'輸出' – topheman
我在HTML文件中添加了更多行,其中包含腳本標籤。在捆綁文件中似乎沒有任何錯誤 – kinghenry14