我正在尝试将信号器用于棋盘游戏应用程序,以便当玩家在一个客户端上移动棋子时,所有客户端都可以更新。我遇到的问题是没有一种明确的方法来抽象应用程序的信号器部分,以便它的使用者不必担心启动连接等事情。我决定跳过生成的代理,而是调用直接的事情。唯一剩下的障碍是,当客户端从服务器接收到请求时,事件回调中的 this 上下文是集线器的,而不是回调所有者的。我想知道是否有办法在上下文中传递。
代码:
Signalr 服务(如管理连接和最终事件的基类):
define('service.signalr', ['jquery'], function ($) {
var connection = $.hubConnection();
var start = function () {
connection.start();
};
return {connection: connection, start: start}
});
具有特定功能的服务 - 在这种情况下处理工件移动:
define('service.game', ['jquery', 'service.signalr'], function ($, signalr) {
var gameHubProxy = signalr.connection.createHubProxy('gameHub');
var addHandler = function (name, callback) {
gameHubProxy.on(name, callback);
}
var moveFigure = function (figureId, targetSpaceId) {
var deferred = $.Deferred();
gameHubProxy.invoke('moveFigure', figureId, targetSpaceId).done(function () { deferred.resolve(); });
return deferred.promise();
};
return { moveFigure: moveFigure, addHandler: addHandler }
});
在服务上调用服务器方法(事件触发器用于执行操作的客户端,因此它不会处理两次):
define('model.space', ['backbone', 'service.game'], function (Backbone, gameService) {
var Space = Backbone.Model.extend({
defaults: { id: 0, figure: null },
moveFigure: function (figureId) {
var self = this;
var spaceId = self.get('id');
gameService.moveFigure(figureId, spaceId).done(function () {
self.trigger('figureMoved', figureId, spaceId, false);
});
}
});
return Space;
});
并尝试收听服务器的响应:
define('view.board', ['jquery', 'underscore', 'backbone', 'helpers', 'bootstrapData', 'service.game', 'aggregate.space'], function ($, _, Backbone, helpers, bootstrapData, gameService, Space) {
var Board = Backbone.View.extend({
initialize: function () {
this.spaces = new Space.Collection(bootstrapData.spaces);
this.listenTo(this.spaces, 'figureMoved', this.updateFigurePosition);
gameService.addHandler('figureMoved', this.updateFigurePosition);
},
updateFigurePosition: function (figureId, spaceId, drawFigure) {
var figure = null;
var oldSpace = this.spaces.find(function (space) {
figure = space.get('figure');
return figure && figure.id == figureId;
});
//code continues, but has already failed on this.spaces
},
});
return Board;
});