我正在尝试通过JavaScript模块化模式加载JSON。我想要3个人使用JSON文件,并加载到DOM中。我相信将其绑定到loadingData
函数后,它指向错误的对象
这是我的代码
(function() {
var people = {
people: [],
init: function() {
this.cacheDom();
this.bindEvents();
this.render();
},
cacheDom: function () {
this.$el = document.querySelector('#peopleModule');
this.$button = this.$el.querySelector('button');
this.$input = this.$el.querySelector('input');
this.$ul = this.$el.querySelector('ul');
this.template = this.$el.querySelector('#people-template').innerHTML;
},
bindEvents: function() {
document.addEventListener('DOMContentLoaded', this.loadingData.bind(this));
},
render: function() {
var data = {
people: this.people
};
this.$ul.innerHTML = Mustache.render(this.template, data);
},
loadingData: function() {
var xhr = new XMLHttpRequest(),
url = 'data/data.json',
_self = this,
result;
xhr.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
result = JSON.parse(this.responseText);
_self.people = result.people;
}
};
xhr.open('GET', url, true);
xhr.send();
}
};
people.init();
})();
这是我的JSON
{
"people": [
{
"name" : "Cameron"
},
{
"name" : "Alex"
},
{
"name" : "Sara"
}
]
}
这是我的HTML
<div id="peopleModule">
<h1>People</h1>
<div>
<input type="text" placeholder="Name">
<button id="addPerson">Add Person</button>
</div>
<ul id="people">
<script id="people-template" type="text/template">
{{#people}}
<li>
<span>{{name}}</span>
<del>X</del>
</li>
{{/people}}
</script>
</ul>
</div>
我将render()
函数放在错误的位置
与this
关键字无关
(function() {
var people = {
people: [],
init: function() {
this.cacheDom();
this.bindEvents();
},
cacheDom: function () {
this.$el = document.querySelector('#peopleModule');
this.$button = this.$el.querySelector('button');
this.$input = this.$el.querySelector('input');
this.$ul = this.$el.querySelector('ul');
this.template = this.$el.querySelector('#people-template').innerHTML;
},
bindEvents: function() {
document.addEventListener('DOMContentLoaded', this.loadingData.bind(this));
},
render: function() {
var data = {
people: this.people
};
this.$ul.innerHTML = Mustache.render(this.template, data);
},
loadingData: function() {
var xhr = new XMLHttpRequest(),
url = 'data/data.json',
_self = this,
result;
xhr.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
result = JSON.parse(this.responseText);
_self.people = result.people;
_self.render();
}
};
xhr.open('GET', url, true);
xhr.send();
}
};
people.init();
})();