我正在尝试学习 socket.io,我决定将 socket.io 添加到我之前构建的主干应用程序中。
所以使用 require.js 我在我的主 app.js 文件中有以下内容:
require(
["jquery",
"underscore",
"backbone",
"bootstrap",
"view/postsview",
"model/model",
"collection/collection",
"socketio",
],
function($, _, B,boot, postsView, model, collection, io) {
$(function() {
window.socket = io.connect('http://127.0.0.1');
var postmodel = new model();
var postcollection = new collection();
window.socket.on('newPost', function (data) {
postcollection.create(data);
});
var posts = new postsView({model:postmodel, collection:postcollection});
posts.render();
$(".maincontainer").html(posts.el);
}
});
如您所见,我的套接字是一个全局变量。因为我想在我的主干视图中向这个套接字发出一些东西。我对 javascript 很陌生,我知道使用全局变量并不总是最好的做法。
我的主干视图如下所示:
var FormView = Backbone.View.extend({
template: _.template(formTemplate),
render: function(){
this.$el.html(this.template());
},
events:{
'click #submit-button' : 'save'
},
save: function(e){
e.preventDefault();
var newname = this.$('input[name=name-input]').val();
var newadress = this.$('input[name=adress-input]').val();
this.collection.create({
name: newname,
adress : newadress,
postedBy: window.userID
});
window.socket.emit('postEvent' , {
name: newname,
adress : newadress,
postedBy: window.userID
});
}
});
最后这是我的 app.js 在服务器端的样子:
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
socket.on('postEvent', function (data) {
socket.broadcast.emit('newPost', data);
});
});
这现在工作正常,但我不确定这是否是使用带有主干的 socket.io 的正确方法。首先,我不喜欢将套接字元素分配为全局变量。是否有另一种方法可以在我的视图中使用到达我的套接字?一般来说,我愿意接受任何建议,我应该如何将 socket.io 与骨干一起使用。