3

$( 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?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Dev8055
  • 33
  • 6
  • Welcome to stackoverflow! I think it would be helpful if you included the HTML from your example so we can see why it might not be working. – John Oct 30 '18 at 15:51
  • @John added example html for reference. – Dev8055 Oct 30 '18 at 15:56
  • Can you please elaborate 'is not executing'? – Aditya Oct 30 '18 at 16:07
  • for example if I call `feature.showItemByIndex(1)` to select second element in the list and execute custom function its not working. It working without $.proxy(...) – Dev8055 Oct 30 '18 at 16:11
  • @asedsami yes I have put a break-point and console.log and its definitely not executing function on the page load. But works for item click event. – Dev8055 Oct 30 '18 at 16:14

1 Answers1

0

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>
John
  • 1,313
  • 9
  • 21