Skip to content

Instantly share code, notes, and snippets.

@maximkott
Created December 7, 2015 11:05
Show Gist options
  • Save maximkott/4086d6c38b60545eddf8 to your computer and use it in GitHub Desktop.
Save maximkott/4086d6c38b60545eddf8 to your computer and use it in GitHub Desktop.

Revisions

  1. maximkott created this gist Dec 7, 2015.
    103 changes: 103 additions & 0 deletions postMessage.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,103 @@
    $(function () {
    console.log('init iframe');

    var $btn = $('#btn');
    var parent = window.parent;

    $btn.on('click', function() {
    parent.postMessage({from: 'iframe'}, '*');
    });

    window.addEventListener('message', function(e) {
    console.log('iframe');
    console.log(e);
    }, false);
    });

    (function (global) {

    function CreditCardForm(id) {
    var self = this;
    var $form = $(id);
    var formEvents = new FormEventListener($form);
    var messenger = new Messenger(window, window.parent);

    self.getFormData = function() {
    var data = {};

    return data;
    };

    self.createCreditCardToken = function() {
    // post
    };

    self.encryptData = function(data) {
    return data;
    };

    self.formDataChanged = function() {
    messenger.dispatch(self.getFormData());
    };

    (function init() {
    formEvents.notifyOnChange(self.formDataChanged);
    messenger.subscribe('cc-form', self.handler)
    })();
    }

    function FormEventListener($form) {
    var self = this;

    self.notifyOnChange = function(listener) {
    $form.on('form-data-changed', listener);
    };

    self.observeInputField = function(id) {
    $form.find(id).on('keyup', self.dataChangeEventHandler);
    };

    self.dataChangeEventHandler = function() {
    $form.trigger('form-data-changed');
    };

    (function init() {
    self.observeInputField('#cc-type');
    self.observeInputField('#cc-number');
    self.observeInputField('#cvv');
    })();
    }

    function Messenger(listenTo, sendTo) {
    var self = this;
    var $doc = $(document);

    self.dispatch = function(topic, data) {
    var e = {
    data: data,
    topic: topic,
    };
    sendTo.postMessage($.toJSON(e), '*');
    };

    self.subscribe = function(topic, subscriber) {
    $doc.on('post-message-data.' + topic, function(e) {
    subscriber(e.data.data);
    });
    };

    self.messageEventHandler = function(e) {
    var data = e.data || {};
    var topic = data.topic || 'global';

    $doc.trigger('post-message-data.' + topic, $.parseJSON(data));
    };

    (function init() {
    listenTo.addEventListener('message', self.messageEventHandler, false);
    })();
    }

    global.creditCardForm = new CreditCardForm('#cc-form');

    })(window);