user3611576
user3611576

Reputation: 37

Handlebars template accessing elements in DOM

I am using this code to render a template in my application -

var venuePage =
    '<div>' +
        '<div id="venuePage">' +
            '<div class="header"><a href="#" class="btn">Back</a><h1>{{title}}</h1></div>' +
            '<div class="scroller">' +
                '<div class="map">' +
                    '<span>{{venue_address1}}, {{venue_town}}, {{venue_postcode}}</span>' +
                '</div>'
            '</div>' +
        '</div>' +
    '</div>';

template = Handlebars.compile(venuePage);
$(".map").text("new text");

After this I want to manipulate .map using jQuery This is not working as at the time that the jQuery code is being run the .map element is not currently in the DOM.

What would be the best way for me to achieve what I need?

Thanks

Upvotes: 0

Views: 3428

Answers (1)

Mateusz Nowak
Mateusz Nowak

Reputation: 4121

You could try something like this

Template:

<script id="template" type="text/x-template">
    <div id="venuePage">
        <div class="header"><a href="#" class="btn">Back</a>
            <h1>{{title}}</h1>
        </div>
        <div class="scroller">
            <div class="map"><span>{{venue_address1}}, {{venue_town}}, {{venue_postcode}}</span>
            </div>
        </div>
    </div>
</script>

and JS (I am using jQuery)

//Asign data first time on load
var data = {
    title : "Sample location",
    venue_address1 : "416 Water St",
    venue_town: "NYC",
    venue_postcode: "10002"
};

var template = $('#template').html();

var templateCompile = Handlebars.compile(template);
$('body').html(templateCompile(data));

//Now some action occurs and it's time to update template

data.venue_address1 = "100 Water St";
data.venue_town = "NYC";
data.venue_postcode = "10000";


$('body').html(templateCompile(data));

Here is a demo app: http://jsfiddle.net/UMBGC/33/

If you need to change structure of div.map then use something like

<div class="map">
     {{#if map}}
     {{map}}
     {{else}}
     <span>{{venue_address1}}, {{venue_town}}, {{venue_postcode}}</span>
     {{/if}}
</div>

and start your application with

var data = {
    title : "Sample location",
    venue_address1 : "416 Water St",
    venue_town: "NYC",
    venue_postcode: "10002", 
    map: false
};

then update data.map to something else

Upvotes: 1

Related Questions