Friday, January 13, 2012

last refactoring for preparing for Jasmine

Joel gave a deep dive into Jasmine testing today, and I have now successfully written a Jasmine test. Woo hoo! I originally wrote this to test and refactored it to be like this earlier today when I realized I needed to wrap the controls in a div so that I might latch onto the div with jQuery. What the HTML and JavaScript do is present a simple form that allows one to duplicate the contexts of one field (at the left) to another field (at the right) by clicking the only button displayed.

 
 

But, how to test this? Well, I had to do another refactoring. My JavaScript ended up in a file called widgetExample.js and looked like this:

var Example = {

   _create: function () {

   },

   _init: function () {

      var self = this;

      self.setup(self.element);

   },

   setup: function (container) {

      var self = this;

      self.options.container = container;

      self.setupAccessibility();

   },

   getOptions: function () {

      var self = this;

      return self.options;

   },

   getOption: function (name) {

      var self = this;

      return self.options[name];

   },

   setOption: function (key, value) {

      var self = this;

      self.options[key] = value;

   },

   setupAccessibility: function () {

      var self = this;

      self.options.container.children(":button").click(function () {

         var leftvalue = self.options.container.children(0).val();

         self.options.container.children("#righty").val(leftvalue);

      });

   },

   options: {

   }

};

$.widget("amd.Example", Example);

 
 

widgetExample.js was called by this HTML:

<!DOCTYPE html>

<html lang="en">

<head>

   <title></title>

   <script src="/Scripts/jquery-latest.js" type="text/javascript"></script>

   <script src="/Scripts/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>

   <script src="/Scripts/underscore.js" type="text/javascript"></script>

   

   <!-- target script -->

   <script type="text/javascript" src="widgetExample.js"></script>

</head>

   <body>

      <div id="wrapper">

         <input id="lefty" />

         <button type="button" id="mover">Move Right -></button>

         <input id="righty" />

      </div>

      <script type="text/javascript">

         $(document).click(function () {

            var target = $('#wrapper');

            var widget = target.Example();

         });

      </script>

   </body>

</html>

No comments:

Post a Comment