2016-11-20 119 views
0

我目前正在學習模塊化JavaScript。我不知道爲什麼我在對象中的功能沒有被識別。這是用於人員申請的列表。有人可以看看嗎? 這是我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

我已經這麼做了。 @Madara Uchiha正在做點什麼。 – Nate

1

這是因爲箭頭功能自動綁定到外部this,這就是window你的情況。你的函數內部的this是不是你認爲它(嘗試在你的任何功能,console.log(this),看看有什麼我指的是)

相反,使用完整版本:init: function() {或短路法版本: init() {

+0

你是什麼意思?因此,如果我在es6中使用箭頭函數,那麼在聲明和調用方法/屬性時,我不必使用關鍵字this? – Nate

+0

是的,Nate。 請參閱:https://rainsoft.io/when-not-to-use-arrow-functions-in-javascript/ 箭頭功能的主要目的是詞彙這個。 –