-
-
Save rambocoder/2492590 to your computer and use it in GitHub Desktop.
Getting live updates and deletes in ChicagoBoss Tutorial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% src/view/greeting/live.html | |
<html><head> | |
<title>Fresh hot greetings!</title> | |
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script> | |
<script> | |
function listen_for_events(timestamp) { | |
$.ajax("/greeting/pull/"+timestamp, { success: | |
function(data, code, xhr) { | |
for (var i=0; i<data.greetings.length; i++) { | |
var creaty = data.greetings[i].create; | |
var delety = data.greetings[i].delete; | |
if (creaty) { | |
var msg = creaty.greeting_text; | |
var msgid = creaty.id; | |
$("#greeting_list").append('<li id="'+msgid+'">'+msg+'</li>'); | |
} | |
if (delety) { | |
var msg = delety.greeting_text; | |
var msgid = delety.id; | |
$("#"+msgid).remove(); | |
} | |
} | |
listen_for_events(data.timestamp); | |
}, | |
}); | |
}; | |
$(document).ready(function() { | |
listen_for_events({{ timestamp }}); | |
}); | |
</script> | |
</head> | |
<body> | |
<ul id="greeting_list"> | |
{% for greeting in greetings %} | |
<li id="{{ greeting.id }}">{{ greeting.greeting_text }}</li> | |
{% empty %} | |
<li>No greetings!</li> | |
{% endfor %} | |
</ul> | |
</body> | |
</html> | |
% priv/init/cb_tutorial_01_news.erl | |
init() -> | |
{ok, WatchId} = boss_news:watch("greetings", | |
fun(created, NewGreeting) -> | |
boss_mq:push("greetings", [{"create", NewGreeting}]); | |
(deleted, OldGreeting) -> | |
boss_mq:push("greetings", [{"delete",OldGreeting}]) | |
end), | |
{ok, [WatchId]}. | |
% src/controller/cb_tutorial_greeting_controller.erl | |
pull('GET', [OldTimestamp]) -> | |
{ok, Timestamp, Greetings} = boss_mq:pull("greetings", | |
list_to_integer(OldTimestamp)), | |
{json, [{timestamp, Timestamp}, {greetings, Greetings}]}; | |
live('GET', []) -> | |
Greetings = boss_db:find(greeting, []), | |
Timestamp = boss_mq:now("greetings"), | |
{ok, [{greetings, Greetings}, {timestamp, Timestamp}]}. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment