oxjs/source/Ox.UI/js/Core/Message.js

53 lines
1.5 KiB
JavaScript

Ox.Message = (function() {
/*
{
oxid: if coming from an iframe
event: string
data: object
}
Ox.Message.post('play', {foo:'bar'});
Ox.Message.post(iframe, {event: 'play', data: {foo:'bar'}});
*/
var that = {},
callbacks = [];
window.addEventListener('message', function(e) {
var data = {};
try {
data = JSON.parse(e.data);
} catch(e) {}
if (data.event == 'init') {
window.oxid = data.data.id;
} else if (data.event) {
callbacks.forEach(function(callback) {
callback(data.event, data.data, data.oxid);
});
} else {
Ox.Log('Message', 'unknown message', e.data);
}
});
that.bind = function(callback) {
callbacks.push(callback);
}
that.post = function(/* [target], event, data */) {
var target, data, event;
if (arguments.length == 2) {
target = window.parent;
event = arguments[0];
data = arguments[1];
} else {
target = Ox.isElement(arguments[0][0]) ? arguments[0][0] : $('#' + arguments[0])[0];
target = target.contentWindow;
event = arguments[1];
data = arguments[2];
}
target.postMessage(JSON.stringify({
event: event,
data: data,
oxid: window.oxid
}), '*');
}
return that;
})();