JS Modular Pattern - public function not executing

Viewed 36

$( document ).ready(function() {
  var feature = (function() {
    var items = $( "#myFeature li" );

    var showItem = function() {
      currentItem = $( this );
      // more code goes here;
    };
 
    var showItemByIndex = function( idx ) {
      $.proxy( showItem, items.get( idx ) );
    };       
 
    items.click( showItem );
 
    return {
      showItemByIndex: showItemByIndex
    };
  })();
 
  feature.showItemByIndex( 0 );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myFeature">
  <ul>
     <li>item 1</li>
     <li>item 2</li>
  </ul>
</div>

The above code snippet from jQuery documentation from here https://learn.jquery.com/code-organization/concepts/

public function feature.showItemByIndex(0) is not executing, can somebody shed some light?

1 Answers

It looks like the showItemByIndex function is called at page load by the line feature.showItemByIndex( 0 ).

The problem is that showItemByIndex doesn't actually do anything useful; It creates a proxy-function to showItem (binding the this keyword) and then doesn't do anything with it.

If you modify the example so the newly created proxy-function is called then the code executes as one would expect it to.

$( document ).ready(function() {
  var feature = (function() {
    var items = $( "#myFeature li" );

    var showItem = function() {
      currentItem = $( this );
      console.log('Show Item',this) // added some logging
    };
 
    var showItemByIndex = function( idx ) {
      $.proxy( showItem, items.get( idx ) )(); // call this proxy function!
    };       
 
    items.click( showItem );
 
    return {
      showItemByIndex: showItemByIndex
    };
  })();
 
  feature.showItemByIndex( 0 );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myFeature">
  <ul>
     <li>item 1</li>
     <li>item 2</li>
  </ul>
</div>

Related