Search code examples
jquerymustachesammy.js

Sammy.js + Mustache gives error in simple example: haystack.indexOf is not a function


Hi all and thanks in advance for taking the time.

I'm experimenting with Sammy.js + Mustache . So, I have created an HTML file that includes everything that should be there:

<html>
    <head>
        <script type="text/javascript" src="jquery-1.6.3.js"></script>
        <script type="text/javascript" src="sammy.js"></script>

        <script type="text/javascript" src="mustache.js"></script>
        <script type="text/javascript" src="sammy.mustache.js"></script>

        <script type="text/javascript" src="application.js"></script>
    </head>
    <body>
        <div id="main">

        </div>

    </body>
</html>

I've taken sammy and mustache files from their github sites.

In application.js there is simply :

$(function() {
    var app = $.sammy('#main', function() {

        this.use('Mustache','ms');

        var search = {};

        this.get('#search', function() {
            var ctx = this;
            ctx.load('data/server.json')
                .then(function(server) {
                    ctx.render('searchForm.ms', server);
                });
        });
    });

    app.run();
});

searchForm.ms is a very simple Mustache template.

It loads the json correctly, then loads the template, but it receives a Document instance. It passes this Document instance to Mustache which instead expects a String, so it fails with haystack.indexOf is not a function because haystack is a Document, not a string.

I also tried changing searchForm.ms to searchForm.txt and got the same error. I'm on a recent version of Firefox, working on file:// urls.

However, this example is so simple it should not fail; where am I wrong?


Solution

  • It seems it is related with lastest jQuery versions (1.6+) and it's browser implementation. I am using lastest version of chrome browser (14.0.8....) and for some reason the success callback while loading template is returning an Document object while the logic for the Sammy framework expects a string. In version 1.4.2 of jQuery the type returned by this call is of type string in the same browser version.

    Walking through the stack I found the issue at line 1499 in Sammy.js:

    dataType: is_json ? 'json' : null,
    

    Fixing it replacing null for 'text'

    dataType: is_json ? 'json' : 'text',
    

    I am not sure if this change is correct. But I hope this info can be useful