Proper way to listen server events like create/update/delete, is to subscribe for those events using the Streaming API.
Here's, an working example how to use Streaming API in VF page.
Unlike Visualforce which has $Api.sessionid
, we don't have such things in LC.
Since LC does not have an sessionid exposed is discussed in this question and here too, there's no straightdown approach to solve this.
As a workaround, you can get the sessionId using the from the controller using approach mentioned in this answer.(Still its an hacky way)
So I did some digging and found a example LC using Streaming API in github thanks to @ShaneMcLaughlin.
I tried to implement a bit simple version and it worked fine in my org.
StreamingTest.cmp
<aura:component controller="StreamingCtrl">
<ltng:require scripts="/resource/streamingapi/js/cometd.js,/resource/streamingapi/js/jquery-1.5.1.js,/resource/streamingapi/js/json2.js,/resource/streamingapi/js/jquery.cometd.js"
afterScriptsLoaded="{!c.doInit}" />
<aura:attribute name="topic" type="string" required="true" />
</aura:component>
StreamingTestController.js
({
doInit : function(component, event, helper) {
console.log('doing init on streamer');
// Retrieve the session id and initialize cometd
var sessionAction = component.get("c.sessionId");
sessionAction.setCallback(this, function(response) {
var state = response.getState();
if(state === "SUCCESS") {
var sessionId = response.getReturnValue();
var authstring = "OAuth " + sessionId;
console.log(sessionId);
//authenticate to the Streaming API
$.cometd.init({
url: window.location.protocol + '//' + window.location.hostname + '/cometd/36.0/',
requestHeaders: { Authorization: authstring },
appendMessageTypeToURL : false
});
$.cometd.subscribe('/topic/'+component.get("v.topic"), function (message){
//print message when new contact is created
console.log(message);
console.log(message.data.sobject);
});
}
});
$A.enqueueAction(sessionAction);
}
})
PushTopic
PushTopic pushTopic = new PushTopic();
pushTopic.Name = 'contactnew';
pushTopic.Query = 'SELECT Id, Name FROM Contact';
pushTopic.ApiVersion = 37.0;
pushTopic.NotifyForOperationCreate = true;
pushTopic.NotifyForFields = 'Referenced';
insert pushTopic;