2016-11-20 19 views
0

私は現在モジュラージャバスクリプトについて学んでいます。なぜ私がオブジェクト内で作った機能が認識されていないのか分かりません。これは人々のアプリケーションのリストです。誰かがそれを見ることができますか? これは私のpeople.jsが機能が認識されないのはなぜですか?

(() => { 
    var people = { 
     people: ['Will', 'Laura'], 
     init:() => { 
      this.cacheDom(); 
      this.bindEvents(); 
      this.render(); 
     }, 
     cacheDom:() => { 
      this.$el = $('#peopleModule'); 
      this.$button = this.$el.find('button'); 
      this.$input = this.$el.find('input'); 
      this.$ul = this.$el.find('ul'); 
      this.template = this.$el.find('#people-template').html(); 
     }, 
     bindEvents:()=>{ 
      this.$button.on('click', this.addPerson.bind(this)); 
     }, 
     render:() =>{ 
      var data = { 
       people: this.people, 
      }; 
      this.$ul.html(Mustache.render(this.template,data)); 
     }, 
     addPerson:() => { 
      this.people.push(this.input.val()); 
      this.render(); 
     } 
    }; 

    people.init(); 
})(); 

をファイルと、ここに私のhtmlは、それははるかに高く評価されるだろう

<!DOCTYPE> 
<html> 

<head> 
    <title>Nate</title> 
</head> 

<body> 
    <div> 
     <h1>This is my Wonderful application</h1> 
    </div> 
    <div id="peopleModule"> 
     <h1>People</h1> 
     <input placeholder="name" type="text"> 
     <button id="addPerson">Add Person</button> 
     <ul id="people"> 
      <script id="people-template" type="text/template"> 
        {{#people}} 
         <li> 
          <span>{{.}}</span> 
          <i class="del">X</i> 
         </li> 
        {{/people}} 
       </script> 
     </ul> 

    </div> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.1.2/mustache.min.js"></script> 
    <script src="people.js" type="text/template"></script> 
</body> 

</html> 

です。 Javascriptはとても圧倒的です!

+0

どのようなエラーが表示されますか? –

答えて

0

text/templateはブラウザで実行されません。たとえpeople.jsがJavaScriptファイルであっても、text/templateとは何をするのかわからないため、ブラウザはブラウザを実行しません。

<script src="people.js"></script> 

type属性を削除します。

+0

私はすでにそうしました。 @マダラうちゃは何かをしていた。 – Nate

1

これは、矢印機能が自動的に外側this(これはwindow)にバインドされているためです。あなたの関数の内部thisは、あなたがそれだと思うものではありません(私が参照してるか見て、あなたの関数のいずれかでconsole.log(this)を試してみてください)

代わりに、フルバージョンを使用します。init: function() {や短いメソッドのバージョンを: init() {

+0

それはどういう意味ですか?したがって、もし私がes6で矢印関数を使用するなら、メソッド/プロパティを宣言して呼び出す際に、キーワードthisを使う必要はありませんか? – Nate

+0

はい、ネイトです。 参照:https://rainsoft.io/when-not-to-use-arrow-functions-in-javascript/ 矢印機能の主な目的は、これの字句です。 –

関連する問題