Осваиваю метод, при котором контент (текст) загружается на веб-страницу из json файла. Контент перед помещение на страницу компилируется с handlebars templates. Javascript файлы с логикой для всего этого, написаны как модули commonjs, скопилированные с помощью browserify. Страницу запускаю с локальный http сервером, установленным с помощью NodeJS npm.
Тестовый пример работал, при попытке применить этот метод к готовой веб-странице, что-то идет не так. Так как только осваиваю этот метод, буду благодарен за помощь.
Итак, имеется:
- webContent.json - в нем хранится контент (текст), который будет подгружен в index.html
- contentProcess.js - содержит функцию, которая послает Ajax запрос к webContent.json, парсит, компилирует с
Handlebars Template
и помещает контент на страницу (с помощью innerHTML) - addContent.js - вызывает функцию из contentProcess.js, подставив нужные переменные. contentProcess.js и
addContent.js написаны и связаны как
commonjs
модули. Затем они компилируются в main.js с помощьюbrowserify
. - index.html - содержит в себе
Handlebars Template
,div
, куда будет помещен контент и линк на main.js
Тестовая версия работала. Когда попытался реализовать этот подход с уже имеющейся веб-страницей, что-то не работает. Консоль жалуется на часть логики из main.js, которая изначально была частью функции в contentProcess.js, которая в тестовом примере работала без проблем (ниже два скриншота):
В чем здесь проблема (в тестовой версии эта функция работала)?
В снипите разбросал фрагменты кода из всех вышеперечисленных файлов (разделив комментариями):
/* --- webContent.json --- */
{
header: "Powerful business",
describtion: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec turpis neque, sodales a faucibus at, viverra luctus urna. Suspendisse dignissim neque dui, in tincidunt arcu.'
}
/* --- contentProcess.js --- */
module.exports = function(jsonDir, templId, finId){
function sendGet(callback) {
/* create an AJAX request using XMLHttpRequest*/
var xhr = new XMLHttpRequest();
/*reference json url taken from: http://www.jsontest.com/*/
/* Specify the type of request by using XMLHttpRequest "open",
here 'GET'(argument one) refers to request type
"http://date.jsontest.com/" (argument two) refers to JSON file location*/
xhr.open('GET', jsonDir);
/*Using onload event handler you can check status of your request*/
xhr.onload = function () {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
} else {
alert(xhr.statusText);
}
};
/*Using onerror event handler you can check error state, if your request failed to get the data*/
xhr.onerror = function () {
alert("Network Error");
};
/*send the request to server*/
xhr.send();
}
//For template-1
var dateTemplate = document.getElementById(templId).innerHTML;
var template = Handlebars.compile(dateTemplate);
sendGet(function (response) {
document.getElementById(finId).innerHTML += template(response);
})
}
/* --- addContent.js --- */
var addContent = require('./contentProcess');
addContent("../data/webContent.json", "main-template", 'maintext');
/* --- main.js (после компиляции addContent.js с помощью browserify) --- */
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var addContent = require('./contentProcess');
/*MAINBLOCK*/
addContent("../data/webContent.json", "main-template", 'maintext');
},{"./contentProcess":2}],2:[function(require,module,exports){
module.exports = function(jsonDir, templId, finId){
function sendGet(callback) {
/* create an AJAX request using XMLHttpRequest*/
var xhr = new XMLHttpRequest();
/*reference json url taken from: http://www.jsontest.com/*/
/* Specify the type of request by using XMLHttpRequest "open",
here 'GET'(argument one) refers to request type
"http://date.jsontest.com/" (argument two) refers to JSON file location*/
xhr.open('GET', jsonDir);
/*Using onload event handler you can check status of your request*/
xhr.onload = function () {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
} else {
alert(xhr.statusText);
}
};
/*Using onerror event handler you can check error state, if your request failed to get the data*/
xhr.onerror = function () {
alert("Network Error");
};
/*send the request to server*/
xhr.send();
}
//For template-1
var dateTemplate = document.getElementById(templId).innerHTML;
var template = Handlebars.compile(dateTemplate);
sendGet(function (response) {
document.getElementById(finId).innerHTML += template(response);
})
}
},{}]},{},[1]);
<!-- фрагмент кода из index.html (на странице используется bootstrap, если это имеет значение) -->
<div id="maintext"> </div>
<script id="main-template" type="text/x-handlebars-template">
{{{header}}} {{{describtion}}} {{{sentence3}}}
</script>