Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebars breaks when passing this.item in Spine.js

I'm attempting to implement the Todo-example given in the Spine.js docs, given here: http://spinejs.com/docs/example_tasks

only I'd like to use Handlebars instead of jQuery.tmpl. I'm using Handlebars 1.0.rc.1

However, when I attempt to call:

template: Handlebars.compile($('#history-template').html()),

render: function(){
    var t = this.template(this.item);
    this.replace(t);
    return this;
}

Handlebars throws an exception at this.template(this.item):

Uncaught TypeError: Cannot call method 'match' of undefined

In the Handlebars lexer, this._input is coming back as undefined.

My template is as follows:

<script id='history-template' type='text/x-handlebars-template'>
    <div class="content-inner {{#if viewed}}msg_unseen{{/if}}">                                             
        <div>{{data}}</div>
    </div>
</script>

Data:

"[{"data":"hello","id":"c-0"}]"

Any ideas?

like image 207
amhou Avatar asked Dec 01 '12 07:12

amhou


1 Answers

The problem appears to be:

  1. a mismatch in the IDs -- your template ID is history-template, but you're trying to select it as $("#my-template).
  2. Your data should be written like {"data":"hello","id":"c-0"} (an object), without the square brackets (which make it an array).

I can run your code once I make those two corrections. See here for a working demo.

var data = { data: "hello", id: "c-0" };
var template = Handlebars.compile($('#history-template').html());
var html = template(data);

(See also here for a confirmation that the #if logic is working correctly.)


Edit

To use the data in the array form -- { data: "hello", id: "c-0" } -- as far as I can tell, in order to use it in a Handlebars template, you need to wrap it in an object:

var obj = { data: "hello", id: "c-0" };
var handlebarsData = { items: obj };

That way you can use the Handlebars iteration form {{#each items}}:

{{#each items}}
    <div class="content-inner {{#if viewed}}msg_unseen{{/if}}">                                             
        <div>{{data}}</div>
    </div>
{{/each}}

Here's the updated Fiddle.

like image 151
McGarnagle Avatar answered Nov 14 '22 22:11

McGarnagle