59 lines
1.4 KiB
JavaScript
59 lines
1.4 KiB
JavaScript
/*@
|
|
Ox.Message <o> Message controller
|
|
@*/
|
|
|
|
Ox.Message = (function() {
|
|
|
|
var that = {},
|
|
callbacks = [];
|
|
|
|
window.addEventListener('message', function(e) {
|
|
var data = {};
|
|
try {
|
|
data = JSON.parse(e.data);
|
|
} catch(e) {}
|
|
Ox.Log('MESSAGE', data)
|
|
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('Core', 'unknown message', e.data);
|
|
}
|
|
});
|
|
|
|
/*@
|
|
.bind <f> Adds message handler
|
|
(callback) -> <o> Ox.Message
|
|
callback <f> Callback function
|
|
|
|
@*/
|
|
that.bind = function(callback) {
|
|
callbacks.push(callback);
|
|
return that;
|
|
};
|
|
|
|
/*@
|
|
.post <f> Sends a message
|
|
(target, event, data) -> <o> Ox.Message
|
|
target <o|s> Ox.$parent or iframe Ox.Element or element id
|
|
event <s> Event name
|
|
data <o> Event data
|
|
@*/
|
|
that.post = function(target, event, data) {
|
|
target = target == Ox.$parent ? window.parent
|
|
: Ox.isElement(target[0]) ? target[0].contentWindow
|
|
: $('#' + target)[0].contentWindow;
|
|
target.postMessage(JSON.stringify({
|
|
event: event,
|
|
data: data,
|
|
oxid: window.oxid
|
|
}), '*');
|
|
return that;
|
|
};
|
|
|
|
return that;
|
|
|
|
})();
|