2013-03-14 2 views
1

저는 간단한 질문 일 수 있으므로 자바 스크립트 및 라이브러리에 익숙하지 않습니다. 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); 

몇 가지해야 할 수도 있습니다 변경 될 수 있지만, 내가 이런 종류의 일반적으로 사용하는 일반적인 작업입니다 태스크.

관련 문제