2013-03-14 116 views
1

我是新来的JavaScript和库,所以这可能是一个简单的问题。我正在尝试使用handlebars.js模板引擎和jQuery来制作几个简单的网页。我一直在遇到的问题是制作多个页面。到目前为止,我有一个不同名称的主页。每个名称都有一个jQuery点击功能。如果我点击一个名称,我只是使用jQuery来更改当前页面。所以基本上,如果你点击一个名字,你会得到一个新的模板和一个该人的图片列表,但是在同一页上说index.html。这个问题是,如果你想回到第一个视图,“后退”按钮现在不起作用。我是否错误地构造了这个?链接应该发送到另一个页面和另一个模板?如果是的话,我该如何根据链接被按下来生成模板。与handlebars.js多个模板

$(document).ready(function(){ 


var source = $(".some-template").html(); 
var template = Handlebars.compile(source); 

data = { date: "today", firstUsers: [ 
{firstName: "person1", pictures: ["pic1", "pic2", "pic3"]}, 
{firstName: "person2", pictures: ["pic1", "pic2", "pic3"]}, 
{firstName: "person3", pictures: ["pic1", "pic2", "pic3"]}, 
{firstName: "person4", pictures: ["pic1", "pic2", "pic3"]}, 
] 
}; 
$(".container").html(template(data)) 

$("li").click(function(){ 
    var name = $(this).html() 
    $.each(data.firstUsers, function(i, item){ 
     if(name === item.firstName){ 
      y = item.pictures 
      return y 
     };//if function 
    });//each function 


    $(".container").hide() 
    var source = $(".some-script").html(); 
    var template = Handlebars.compile(source); 
    datas = {namer: name, pictures: y,} 
    //console.log(datas.pictures) 
    $(".content").html(template(datas)) 
});//click function 
});//document ready 

回答

2

使用最佳做法,您应该可能有与每个页面关联的URL。如果您使用window.history.pushState,则有一种相当简单的方法可以使后退/前进按钮正常工作。

所以基本上它的工作原理如下:

  1. 每次加载新的模板,推一个新的浏览器状态。
  2. 收听onpopstate事件,并在触发时加载相应的模板。

我分开你的函数以上成两个独立的功能,resusability:

function loadUser(name) { 
    var y; 
    $.each(data.firstUsers, function(i, item){ 
     if(name === item.firstName){ 
      y = item.pictures 
      return y 
     };//if function 
    });//each function 

    $(".container").hide() 
    var source = $(".some-script").html(); 
    var template = Handlebars.compile(source); 
    datas = {namer: name, pictures: y,} 
    //console.log(datas.pictures) 
    $(".content").html(template(datas)) 
    window.history.pushState(null, null, name); 
} 

// Find the name of the user 
// TODO: change the regex to match your URL scheme 
function popStateResponder() { 
    var name = window.location.pathname.match(/\w+$/)[0]; 
    loadUser(name); 
} 

$("li").click(function(){ 
    var name = $(this).html(), 

    loadUser(name); 
});//click function 

$(window).on('popstate', popStateResponder); 

有几件事情,可能需要改变,但这是一般工作流程我一般使用的这种任务。