2013-03-14 115 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); 

有幾件事情,可能需要改變,但這是一般工作流程我一般使用的這種任務。