gpt4 book ai didi

javascript - js文件结构,返回值?

转载 作者:太空宇宙 更新时间:2023-11-04 16:13:17 25 4
gpt4 key购买 nike

背景故事:我正在研究 js 文件结构并构建一个助手,在其中获取 Handlebars 模板并填充它(将在 Handlebars 驱动的样式指南工具、制造器中使用)。

我的returnTemplate()函数返回未定义,我不明白为什么?它确实进入 renderTemplate() 并执行其操作,但返回值无法一路返回到按钮单击。

jsfiddle

var Button = (function() {
function init() {
$('.js-template-trigger').on('click', function() {
var context = {
name: 'John Wick'
}

var value = TemplateHelper.returnTemplate('demo-template', context);
console.log('value:', value);
});
}

return {
init: init
};
})();

$(function() {
Button.init();
});


var TemplateHelper = (function() {
function getTemplate(templateId, callBack, context) {
//$.get('/data/templates.html#' + templateId).done(callBack);
console.log('what is:', $('#demo-template')[0].outerHTML);

callBack($('#demo-template')[0].outerHTML);
}

function renderTemplate(source, context) {
console.log('renderTemplate');

var template = Handlebars.compile(source);
var html = template(context);

console.log('renderTemplate html:', html);
console.log('renderTemplate html inner:', $(html).html());

return $(html).html();
}

function returnTemplate(templateId, context) {
var callBack = function(data) {
renderTemplate(data, context);
}

return getTemplate(templateId, callBack, context);
}

function appendToTemplate(templateId, context, targetAppend) {
var callBack = function(data) {
if (data !== undefined) {
var html = renderTemplate(source, context);
$(html).appendTo($(targetAppend));
}
}

getTemplate(templateId, callBack, context);
}

return {
returnTemplate: returnTemplate
};
})();

html

<button type="button" class="js-template-trigger">click me</button>

<script id="demo-template" type="text/x-handlebars-template">
<div style="height: 50px; width: 100%; background-color: deepskyblue;">{{name}}</div>
</script>

最佳答案

函数returnTemplate如果你的函数 getTemplate 会返回一些东西返回一些东西。所以你可以添加return在指令之前callBack($('#demo-template')[0].outerHTML); 。同样,您的回调函数必须返回一些内容:add return在指令之前renderTemplate(data, context); (在 var 回调的定义中)。

关于javascript - js文件结构,返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41283942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com