JavaScript 模块模式不起作用

JavaScript module pattern not working

本文关键字:不起作用 模式 模块 JavaScript      更新时间:2023-09-26

我正在尝试根据在线的一些示例在我的代码中实现模块模式,我试图实现的是简单地将我的html中的按钮单击事件绑定到一个函数(不起作用),下面是我的HTML:

<!DOCTYPE html>
<html>
  <head>
    <script data-require="angular.js@*" data-semver="1.3.7" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script>
    <script data-require="jquery@*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>
  <body>
    <h1>Hello Plunker!</h1>
    <input type="button" id="btn-msg" value="click me"/>
  </body>
</html>

这是我的JS:

//CRUD Start
var Rutherford = Rutherford || {};
Rutherford.crud = function() {
  function _readLists() {
    alert("am here");
  }
  return {
    readLists: _readLists
  }
}
Rutherford.Initiate = function() {
  $("#btn-msg").click(Rutherford.crud.readLists);
}
$(function() {
  Rutherford.Initiate();
});

这里还有一个指向我的 plunker 的链接:http://plnkr.co/edit/tA94lzMPHkUOr8QuyJK8?p=preview

我试图实现的只是将按钮绑定到函数。

你需要调用匿名函数,而不是赋值它。 请参阅下面的()

Rutherford.crud = (function() {
  function _readLists() {
    alert("am here");
  }
  return {
    readLists: _readLists
  }
}());

以下是包含此更改的更新 plunkr:http://plnkr.co/edit/uiWHmtkMFEKywvFRk6DF?p=info

我相信

埃文·诺尔斯想这样说:

//CRUD Start
var Rutherford = Rutherford || {};
Rutherford.crud = (function() {
  function _readLists() {
    alert("am here");
  }
  return {
    readLists: _readLists
  }
})( );
Rutherford.Initiate = function() {
  $("#btn-msg").click(Rutherford.crud.readLists);
}
$(function() {
  Rutherford.Initiate();
});

如果您可以将Rutherford用作单例,这将正常工作。