I’m working through a SignalR demo that displays database info in a list when a button is hit.
My Hub has 2 functions: One to remove DB objects from a list, and one to re-add DB objects to that list.
These functions are performed in my View and perform great when I only have the page open once. But if I open the page in another tab (can be the same browser or a different one), the pages do not stay in sync.
Meaning, when one page’s button is hit, the other page is not displaying the data correctly.
Often times one page will do fine, while the other will perform the remove but not the add! It’s mind-boggling. They should just be reflections of each other from my understanding.
Has anyone else run into something similar?
Thanks in advance for any help!
Here’s my Hub :
[HubName("hubtest")]
public class HubTest : Hub
{
CmsContext db = new CmsContext();
public void showdata()
{
var f = from x in db.Data
select x;
Clients.remove();
Clients.add(f);
}
}
And here’s the javascript in my View for the functions:
<script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-0.5.2.min.js" type="text/javascript"></script>
<script src="/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var hubtest = $.connection.hubtest;
hubtest.remove = function () {
//clear list of any prior values
var list = document.getElementById('dataList');
while (list.hasChildNodes()) {
list.removeChild(list.childNodes[0])
}
};
hubtest.add = function (data) {
//populate with updated values
for (var i = 0; i < data.length; i++) {
var element = data[i];
$('#dataList').append('<li>' + element.Question + '</li>');
}
};
$("#broadcast").click(function () {
hubtest.showdata();
});
// Start the connection
$.connection.hub.start();
});
</script>
<input type="button" id="broadcast" value="broadcast" />
<ul id="dataList">
</ul>
First of all thanks for your replies. I really appreciate your feedback!
I eventually got it to where my pages are staying in sync when open in multiple tabs by altering how my data is sent to the View.
Where I was performing the for loop in my Javascript to display each piece of data, now I am doing that in my Hub like so:
Then my Javascript is just appending that FAQ question to the list:
Sending just a simple string of my data to be printed individually seems to allow my page to stay in sync.
Before the data I was sending was a list of DB objects and my Javascript was looping through each and adding that object’s Question column to the list. Not sure why this was such an issue – especially since it would work on one open tab but not all open tabs – but that simple change fixed my site sync issues.
Thanks again!