title: Spying a function called by jQuery 'change' with RequireJS and Jasmine
body: <p>I'm rather new at both RequireJS and Jasmine so I'm having a little trouble setting up a few basic tests to start with. I've found a lot of info on how to set up the two together, and have it working. However I have an interesting problem I can't seem to fix.</p>
  
  <p>Unfortunately I'm not sure the best way to word the problem so here's some code:</p>
  
  <p>main.js:</p>
  
  <pre><code>require(['jquery', 'manipulate'], function($, Manipulate) {
    var manipulate = new Manipulate;
    $(document).on('change', 'td input', function() {
      manipulate.pushChange();
    });
  });
  </code></pre>
  
  <p>manipulate.js:</p>
  
  <pre><code>define(function() {
    function Manipulate() {
      //
    };
  
    Manipulate.prototype.pushChange = function() {
      return true;
    };
  
    return Manipulate;
  });
  </code></pre>
  
  <p>ManipulateSpec.js:</p>
  
  <pre><code>describe('Manipulate', function() {
    var manipulate;
  
    beforeEach(function() {
      var flag = false;
  
      // Load fixtures into the HTML
      loadFixtures('ManipulateFixture.html');
  
      // Require the manipulate.js file
      require(['jquery', 'manipulate', 'main'], function(jQuery, Manipulate) {
        manipulate = new Manipulate;
  
        // Define any spies
        spyOn(manipulate, 'pushChange');
  
        flag = true;
      });
  
      // Wait for manipulate.js to load before running tests
      waitsFor(function() {
        return flag;
      });
    });
  
    it('should call pushChange after changing a cell', function() {
      $('td input').eq(0).trigger('change');
      expect(manipulate.pushChange).toHaveBeenCalled();
    });
  });
  </code></pre>
  
  <p>(Removed some extra code)</p>
  
  <p>If I <code>console.log</code> inside <code>Manipulate.pushChange</code>, it is firing. The problem is, the <code>Manipulate</code> object that is being spied on isn't the same object that is passed as an argument in the <code>main.js</code> file. So adding <code>manipulate.pushChange</code> in my <code>it()</code> block makes the test pass.</p>
  
  <p>I found an answer for Backbone.js apps, which calls <a href="http://backbonejs.org/#View-delegateEvents" rel="nofollow"><code>delegateEvents</code></a>. I'm not sure if there is a similar solution for vanilla Javascript, jQuery, etc. but I can't find one.</p>
  
  <p>Is there a better way to structure my files, potentially putting my jQuery event handlers in the manipulate module? Or just a way to "copy" events between the two objects? I don't even believe using <code>createSpy</code> will help me much in this case.</p>