Search code examples
javascriptfancyboxmodal-dialogsammy.js

SammyJS json store demo - how to create modal product popup?


Does anyone have an example of making the product details of the SammyJS json store demo show up in a modal plugin like FancyBox?

Here's the block of code from json store - what do I need to do to present it in a model FancyBox?

this.get('#/item/:id', function(context) {
  this.item = this.items[this.params['id']];
  if (!this.item) { return this.notFound(); }
  this.partial('templates/item_detail.template');
});

Solution

  • You probably want to use Sammy's RenderContext render() method:

    this.get('#/item/:id', function(context) {
      this.item = this.items[this.params['id']];
      if (!this.item) { return this.notFound(); }
      this.render('templates/item_detail.template').then(function(content) {
        $.fancybox({
            content: content,
            // set box size to fit the product details
            autoDimensions: false,
            width: 800,
            height: 500
        });
      });
    });
    

    EDIT As pointed out by @drozzy the location bar will still change with this method. To work around this behaviour we will need to intercept the click on the link that should open the popup and explicitly start Sammy's route:

    $(document).delegate("a[href^=#/item/]", "click", function(linkElement) {
    
      // Determine and explicitly start Sammy's route for the clicked link
      var path = linkElement.currentTarget.href.replace(/^[^#]*/, "");
      Sammy('#main').runRoute('get', path);
    
      // cancel the default behaviour
      return false;
    });
    

    Note that this example uses a selector matching links with routes starting with #/item/. If this is not specific enough one should probably something more suitable, e.g. marker classes.

    (This uses jQuery 1.4.3, as used in the JSON Store demo.)