add Ox.Message for message passing between frame and parent

This commit is contained in:
j 2013-02-24 07:37:20 +00:00
parent 916a175849
commit 47efc7377a
3 changed files with 107 additions and 0 deletions

View file

@ -287,6 +287,30 @@ Ox.load.UI = function(options, callback) {
Ox.$document = Ox.UI.$document = $(document);
Ox.$head = Ox.UI.$head = $('head');
Ox.$window = Ox.UI.$window = $(window);
Ox.$parent = {
postMessage: function(event, message) {
Ox.Message.post(event, message);
return this;
},
onMessage: function() {
var callback;
if (Ox.isObject(arguments[0])) {
Ox.forEach(arguments[0], function(callback, event) {
Ox.Message.bind(function(evt, data, oxid) {
if (Ox.isUndefined(oxid) && event == evt) {
callback(data);
}
});
});
} else {
callback = arguments[0];
Ox.Message.bind(function(event, data, oxid) {
Ox.isUndefined(oxid) && callback(event, data);
});
}
return this;
}
};
// fixme: is this the right place to do this?
$.browser.mozilla && Ox.$document.on('dragstart', function() {
return false;

View file

@ -89,6 +89,36 @@ Ox.Element = function(options, self) {
.addClass('OxElement')
.on({mousedown: mousedown});
if (self.options.element == '<iframe>') {
that.on('load', function() {
Ox.Message.post(that, 'init', {id: that.oxid});
});
that.onMessage = function(callback) {
var callback;
if (Ox.isObject(arguments[0])) {
Ox.forEach(function(callback, event) {
Ox.Message.bind(arguments[0], function(evt, data, oxid) {
if (that.oxid ==oxid && event == evt) {
callback(data);
}
});
});
} else {
callback = arguments[0];
Ox.Message.bind(function(event, data, oxid) {
if (that.oxid == oxid) {
callback(event, data);
}
});
}
return that;
};
that.postMessage = function(event, data) {
Ox.Message.post(that, event, data);
return that;
};
}
setTooltip();
function mousedown(e) {

View file

@ -0,0 +1,53 @@
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;
})();