【问题标题】:JS Modular Pattern - public function not executingJS 模块化模式 - 公共功能未执行
【发布时间】:2019-04-03 17:11:59
【问题描述】:

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

上面的代码 sn-p 来自这里的 jQuery 文档https://learn.jquery.com/code-organization/concepts/

公共函数feature.showItemByIndex(0) 没有执行,有人能解释一下吗?

【问题讨论】:

  • 欢迎来到stackoverflow!我认为如果您包含示例中的 HTML 将会很有帮助,这样我们就可以了解它为什么不起作用。
  • @John 添加了示例 html 以供参考。
  • 您能否详细说明“未执行”?
  • 例如,如果我调用feature.showItemByIndex(1) 来选择列表中的第二个元素并执行自定义函数,则它不起作用。它在没有 $.proxy(...) 的情况下工作
  • @asedsami 是的,我已经放置了一个断点和 console.log,它绝对不会在页面加载时执行功能。但适用于项目点击事件。

标签: javascript jquery modular


【解决方案1】:

看起来showItemByIndex 函数在页面加载时由feature.showItemByIndex( 0 ) 行调用。

问题是showItemByIndex 实际上并没有做任何有用的事情;它为showItem 创建一个代理函数(绑定this 关键字),然后不做任何事情。

如果您修改示例以便调用新创建的代理函数,那么代码将按预期执行。

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

【讨论】:

  • 感谢您的及时响应,按预期工作,并将进行更多测试。
猜你喜欢
  • 1970-01-01
  • 2020-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-12
  • 2011-04-26
  • 2020-12-06
  • 2021-11-04
相关资源
最近更新 更多