Skip to content

Instantly share code, notes, and snippets.

@harmony7
Last active March 4, 2016 08:57
Show Gist options
  • Save harmony7/4370f34c2aed2409359e to your computer and use it in GitHub Desktop.
Save harmony7/4370f34c2aed2409359e to your computer and use it in GitHub Desktop.
LiveResource updated API
-- VALUE
import { JsonValueInterest, LiveResource } from 'liveresource';
class TimeValueInterest extends JsonValueInterest {
transform(obj) {
return obj.time;
}
}
// Automatic start
const timeValueResource = new LiveResource("http://test.liveresource.org/test", {
interest: TimeValueInterest
});
timeValueResource.on('value', (data) => {
console.log(data);
});
// Manual start
const timeValueManualStartResource = new LiveResource({interest: TimeValueInterest});
fetch("http://test.liveresource.org/test")
.then((response) => {
const json = response.json();
console.log(json.time);
timeValueManualStartResource.start(response.headers);
});
timeValueManualStartResource.on('value', (data) => {
console.log(data);
});
-- CHANGES
import { JsonChangesInterest, LiveResource } from 'liveresource';
class TimeChangesInterest extends JsonChangesInterest {
transform(obj) {
// Format is "+xx"
const change = obj['time:change'] || "+0";
let c = change.trim();
let sign = "+";
let value = 0;
if (c.charAt(0) === "+" || c.charAt(0) === "-") {
sign = c.charAt(0);
c = c.substring(1);
}
value = parseInt(c, 10);
return { sign, value };
}
}
let currentTime = 0;
const timeChangesResource = new LiveResource({interest: TimeChangesInterest});
fetch("http://test.liveresource.org/test")
.then((response) => {
const json = response.json();
currentTime = json.time;
console.log(currentTime);
timeChangesResource.start(response.headers);
});
timeChangesResource.on('changes', (data) => {
const multiplier = (data.sign === "+") ? 1 : -1;
currentTime += multiplier * data.value;
console.log(currentTime);
});
--
LiveResource
constructor
new LiveResource(url, options) or new LiveRsource(options);
if the first parameter is a string, then it's treated the same as {url}
and merged in with the rest of the options
if url is provided, then in the case of a ValueParser an initial fetch
will be performed that will also trigger a value event and then automatically
call start() with the headers return from that fetch.
if url is not provided, then it's necessary for caller to to call start()
at a later time and pass in a set of headers to begin the process.
options:
interest - a class or instance of a class that is an Interest.
If omitted, JsonValueInterest is the default.
start(headers)
starts LiveResource process with the passed-in headers.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment