所以我正在尝试做的,并且我在这里做了一个小示例项目,当用户正在编辑表格中的单元格时,该单元格将禁用该页面上的其他所有人。都好。在这里我进行设置,以便当用户进入一个单元格时,它会禁用其他所有人,并且在模糊/退出单元格时,它会清除。现在问题是,如果一个人在一个单元格中,它会在其他人的屏幕上禁用。但是,如果有人刷新或者新用户进入页面,即使主用户仍在该单元格中,也不会禁用该用户。有没有一种方法可以让SignalR知道有人在使用特定细胞时使用它,而不仅仅是当他进入/退出细胞时?
C#代码:
public class ChatHub : Hub
{
public void Send(string name, string message, bool boolean)
{
// Call the broadcastMessage method to update clients.
Clients.Others.broadcastMessage(name, message, boolean);
}
}
HTML代码:
<table id="table">
<thead>
<tr>
<th>HeaderOne</th>
<th>HeaderTwo</th>
<th>HeaderThree</th>
</tr>
</thead>
<tbody>
@for(int i = 0; i < 3; i++)
{
<tr>
<td><input class="tdInput" /></td>
<td><input class="tdInput" /></td>
<td><input class="tdInput" /></td>
</tr>
}
</tbody>
</table>
Javascript代码:
$(function () {
var conn = $.connection.chatHub;
conn.client.broadcastMessage = function (col, row, boolean) {
var cell = $("#table tr:eq(" + row + ") td:eq(" + col + ")");
cell.find("input").prop('disabled', boolean);
};
$.connection.hub.start().done(function () {
$(".tdInput").on('focus', function () {
var col = $(this).parent().index();
var row = $(this).closest('tr').index() + 1;
conn.server.send(col, row, true);
});
$(".tdInput").on('blur', function () {
var col = $(this).parent().index();
var row = $(this).closest('tr').index() + 1;
conn.server.send(col, row, false);
});
});
});
以下是Christoph评论中选项#2的简单实现:
在connection.hub.start()中,添加:
conn.server.refresh();
在JS中:
conn.client.resendStatus = function () {
if ($('input:focus').length > 0) {
var focused = $(":focus");
var col = focused.parent().index();
var row = focused.closest('tr').index() + 1;
conn.server.send(col, row, true);
}
};
在中心:
public void Refresh()
{
Clients.Others.resendStatus();
}
在我看来,有两种可能的解决方案:
第二个选项更容易处理,因为您不需要任何状态跟踪,尤其是没有超时。但是,您将在加载页面后有一段短暂的时间,其他人编辑的单元格将暂时解锁。
您可以添加setTimeout,这将每秒发送锁定/状态,直到用户在单元格中。
$(function () {
var conn = $.connection.chatHub;
conn.client.broadcastMessage = function (col, row, boolean) {
var cell = $("#table tr:eq(" + row + ") td:eq(" + col + ")");
cell.find("input").prop('disabled', boolean);
};
$.connection.hub.start().done(function () {
var flag=false;
$(".tdInput").on('focus', function () {
flag=true;
while(flag)
{
setTimeout(function(){
var col = $(this).parent().index();
var row = $(this).closest('tr').index() + 1;
conn.server.send(col, row, true);
},1000);
}
});
$(".tdInput").on('blur', function () {
flag=false;
var col = $(this).parent().index();
var row = $(this).closest('tr').index() + 1;
conn.server.send(col, row, false);
});
});
});