Skip to content

Instantly share code, notes, and snippets.

@walter
Last active March 23, 2018 16:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save walter/afecb3b2b1b24246acb3 to your computer and use it in GitHub Desktop.
Save walter/afecb3b2b1b24246acb3 to your computer and use it in GitHub Desktop.
Example third party widget stuff with Ember.js and ember-cli

Page calling third party widget:

<html>
  <head>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
  </head>
  <body>
    <script class="at-widget-loader" src="proof/widget.js" type="text/javascript" async></script>
  </body>
</html>

proof/widget.js

(function() {
  // Globals for tracking instances of widget
  // i.e. there may be more than one on the page, each called with different params
  if (!window.ProofWidget) { window.ProofWidget = {}; };
  var ProofWidget = window.ProofWidget;

  // To keep track of which embeds we have already processed
  if (!ProofWidget.foundEmbeds) ProofWidget.foundEmbeds = [];
  var foundEmbeds = ProofWidget.foundEmbeds;

  // Localize jQuery variable
  var jQuery;

  /******** Load jQuery if not present *********/
  if (window.jQuery === undefined || window.jQuery.fn.jquery !== '2.1.1') {
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type","text/javascript");
    script_tag.setAttribute("src",
                            "http://code.jquery.com/jquery-2.1.1.min.js");
    if (script_tag.readyState) {
      script_tag.onreadystatechange = function () { // For old versions of IE
        if (this.readyState === 'complete' || this.readyState === 'loaded') {
          scriptLoadHandler();
        }
      };
    } else { // Other browsers
      script_tag.onload = scriptLoadHandler;
    }
    // Try to find the head, otherwise default to the documentElement
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
  } else {
    // The jQuery version on the window is the one we want to use
    jQuery = window.jQuery;
    main();
  }

  /******** Called once jQuery has loaded ******/
  function scriptLoadHandler() {
    // Restore $ and window.jQuery to their previous values and store the
    // new jQuery in our local jQuery variable
    jQuery = window.jQuery.noConflict(true);
    // Call our main function
    main();
  }

  function htmlTemplate(tagId, options) {
    headline = options.headline;
    summary = options.questionSummary;

    var html = '<div class="at-widget" id="' + tagId + '">';
    html += '<h4>' + headline + '</h4>';
    html += '<div class="description"><p>' + summary + '</p></div>';
    html += '<div id="poc-container" class="at-ember-embed"></div>';
    html += '</div>';

    return html;
  }

  function addJSIfNecessary(jsUrls) {
    jQuery.each(jsUrls, function(key, value) {
      var jsSelector = "script[src='"+ value + "']";

      if (!jQuery(jsSelector).length) {
        var jsScript = jQuery("<script>", {
          type: "text/javascript",
          src: value
        });

        jsScript.appendTo('body');
      }
    });
  }

  function addCssLinksIfNecessary(cssUrls) {
    jQuery.each(cssUrls, function(key, value) {
      var cssSelector = "link[href='"+ value + "']";

      if (!jQuery(cssSelector).length) {
        var cssLink = jQuery("<link>", {
          rel: "stylesheet",
          type: "text/css",
          href: value
        });

        cssLink.appendTo('head');
      }
    });
  }

  /******** Our main function ********/
  function main() {
    jQuery(document).ready(function($) {
      // We can use jQuery here

      // load css, only if it hasn't been loaded
      var cssUrls = ['proof/widget.css',
                     'proof/poc/assets/vendor-d41d8cd98f00b204e9800998ecf8427e.css',
                     'proof/poc/assets/poc-de3c495d5da3bffcdc865aaa60f76ab3.css'];

      addCssLinksIfNecessary(cssUrls);

      var metaConfig = jQuery("<meta>", {
        name: 'poc/config/environment',
        content: '%7B%22modulePrefix%22%3A%22poc%22%2C%22environment%22%3A%22production%22%2C%22locationType%22%3A%22none%22%2C%22EmberENV%22%3A%7B%22FEATURES%22%3A%7B%7D%7D%2C%22APP%22%3A%7B%22rootElement%22%3A%22%23poc-container%22%7D%2C%22contentSecurityPolicyHeader%22%3A%22Content-Security-Policy-Report-Only%22%2C%22contentSecurityPolicy%22%3A%7B%22default-src%22%3A%22%27none%27%22%2C%22script-src%22%3A%22%27self%27%22%2C%22font-src%22%3A%22%27self%27%22%2C%22connect-src%22%3A%22%27self%27%22%2C%22img-src%22%3A%22%27self%27%22%2C%22style-src%22%3A%22%27self%27%22%2C%22media-src%22%3A%22%27self%27%22%7D%2C%22exportApplicationGlobal%22%3Afalse%7D'
      });

      metaConfig.appendTo('head');

      var jsUrls = ['proof/poc/assets/vendor-af96473d63ec4c706bbaf5b12865fcf2.js',
                    'proof/poc/assets/poc-32cb351937fd0e39f83ba8487fe4392f.js']

      addJSIfNecessary(jsUrls);

      jQuery('.at-widget-loader').each(function(i) {
        if (foundEmbeds.indexOf(this) < 0) {
          // parse our parameters
          // set defaults, use data attributes where possible
          // hidden divs where we need html
          var tagId = 'at-question-' + i.toString();
          if (jQuery(this).data('tag-id') && jQuery(this).data('tag-id').length > 0) tagId = jQuery(this).data('tag-id');

          var tagIdSelector = "#"+tagId;

          var paramsDiv;
          jQuery('div.at-widget-attributes').each(function () {
            var associatedTagId = jQuery(this).data('tag-id');
            if (typeof associatedTagId !== "undefined" && associatedTagId === tagId) {
              paramsDiv = this;
            }
          })

          var headline = 'HEADLINe';

          var questionSummary = 'SUMMARY';

          var options = {
            headline: headline,
            questionSummary: questionSummary
          };

          // add our HTML
          jQuery(this).after(htmlTemplate(tagId, options));

          foundEmbeds.push(this);
        }
      })
    });
  }
})(); // We call our anonymous function immediately

In our ember-cli project (ember new poc with only change in config/environment.js

/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'poc',
    environment: environment,
    locationType: 'none',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      rootElement: '#poc-container'
    }
  };

  if (environment === 'development') {
    // ...
  }

  if (environment === 'test') {
    // ...
  }

  if (environment === 'production') {

  }

  return ENV;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment