Search code examples
javascriptsammy.js

Callbacks in Sammy


I have this peice of code - I just need to add a class on a DOM element which will be rendered in the template. However, this fails to work!

    this.get('#/:post_id', function(context){
            context.app.swap('');
         this.load('/post/' +  this.params['post_id'])
             .then(function(candidates){
                  $.each(candidates[1], function(i, candidate){
                      context.render("static/templates/candidate.template", {candidate:candidate})
                     .appendTo(context.$element());
             });
         })
        .then(function(){
            $('h3').addClass('custom_class');
         });

Candidate.template:

<div>
  <h3>Name : <%= candidate.name %> </h3>
  ...
  ...
</div>

Solution

  • I'm new to Sammy, so take this with a grain of salt. I think it is failing because your first .then() doesn't return anything (like the context), which means the next .then() has nothing to work on.

    Does something like this work ?

    this.get('#/:post_id', function(context){
            context.app.swap('');
         this.load('/post/' +  this.params['post_id'])
             .then(function(candidates){
                  $.each(candidates[1], function(i, candidate){
                      context.render("static/templates/candidate.template", {candidate:candidate})
                     .appendTo(context.$element());
             });
             return context;
         })
        .then(function(){
            $('h3').addClass('custom_class');
         });
    });