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

60 lines
1.4 KiB
JavaScript
Raw Normal View History

2013-02-24 09:36:08 +00:00
/*@
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) {}
2013-02-25 05:57:00 +00:00
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 {
2013-02-24 09:36:08 +00:00
Ox.Log('Core', 'unknown message', e.data);
}
});
2013-02-24 10:57:37 +00:00
/*@
.bind <f> Adds message handler
(callback) -> <o> Ox.Message
callback <f> Callback function
@*/
that.bind = function(callback) {
callbacks.push(callback);
2013-02-24 10:57:37 +00:00
return that;
2013-02-24 09:36:08 +00:00
};
2013-02-24 10:57:37 +00:00
/*@
.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
2013-02-25 04:54:40 +00:00
: Ox.isElement(target[0]) ? target[0].contentWindow
: $('#' + target)[0].contentWindow;
target.postMessage(JSON.stringify({
event: event,
data: data,
oxid: window.oxid
}), '*');
2013-02-24 10:57:37 +00:00
return that;
2013-02-24 09:36:08 +00:00
};
return that;
2013-02-24 09:36:08 +00:00
})();