2013-02-24 09:36:08 +00:00
|
|
|
/*@
|
|
|
|
Ox.Message <o> Message controller
|
|
|
|
@*/
|
|
|
|
|
2013-02-24 07:37:20 +00:00
|
|
|
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)
|
2013-02-24 07:37:20 +00:00
|
|
|
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 07:37:20 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2013-02-28 15:42:06 +00:00
|
|
|
// Defined here so one can just load Message.js in addtion to Ox.js
|
|
|
|
Ox.$parent = {
|
|
|
|
postMessage: function(event, message) {
|
|
|
|
Ox.Message.post(Ox.$parent, event, message);
|
|
|
|
return this;
|
|
|
|
},
|
|
|
|
onMessage: function() {
|
|
|
|
var callback;
|
|
|
|
if (Ox.isObject(arguments[0])) {
|
|
|
|
Ox.forEach(arguments[0], function(callback, event) {
|
|
|
|
Ox.Message.bind(function(event_, data, oxid) {
|
|
|
|
if (event_ == event && Ox.isUndefined(oxid)) {
|
|
|
|
callback(data || {});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
callback = arguments[0];
|
|
|
|
Ox.Message.bind(function(event, data, oxid) {
|
|
|
|
if (Ox.isUndefined(oxid)) {
|
|
|
|
callback(event, data || {});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2013-02-24 10:57:37 +00:00
|
|
|
/*@
|
|
|
|
.bind <f> Adds message handler
|
|
|
|
(callback) -> <o> Ox.Message
|
|
|
|
callback <f> Callback function
|
|
|
|
|
|
|
|
@*/
|
2013-02-24 07:37:20 +00:00
|
|
|
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
|
2013-02-28 15:42:06 +00:00
|
|
|
: Ox.$('#' + target)[0].contentWindow;
|
2013-02-24 07:37:20 +00:00
|
|
|
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
|
|
|
};
|
|
|
|
|
2013-02-24 07:37:20 +00:00
|
|
|
return that;
|
2013-02-24 09:36:08 +00:00
|
|
|
|
2013-02-24 07:37:20 +00:00
|
|
|
})();
|