user6127082
user6127082

Reputation:

Why is my function not being recognized?

I'm currently learning about modular javascript. I don't know why my the functions that I made in a object aren't being recognized. This is for a list of people application. Can someone take a look at it? This is my people.js file

(() => {
    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();
})();

And here is my 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>

It would be much appreciated. Javascript is just so overwhelming!

Upvotes: 0

Views: 535

Answers (2)

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174937

That's because arrow functions are automatically bound to the outside this, which is window in your case. The this inside of your functions isn't what you think it is (try console.log(this) in any of your functions, to see what I'm referring to)

Instead, use the full version: init: function() { or the short method version: init() {

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324600

text/template is not going to get run by the browser. Even if people.js is a JavaScript file, your browser won't run it because it doesn't know what to do with text/template.

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

Remove type attribute.

Upvotes: 0

Related Questions