Captain John
Captain John

Reputation: 1891

Sammy JS Routing in click event

Just wanted to make sure I was doing the right thing with SammyJS as it doesn't really feel like I am.

I have a click event handled in code, that must be handled in code. So.. I want the following to happen:

  1. User clicks button and runs code.
  2. Code navigates to new route event.
  3. The route handler code is invoked. (Updating the URL too)

I've found the following way of doing this:

  1. User clicks button - Make call to both EventContext.redirect method and app.runRoute methods.

I'm new to SammyJS but I have used durandal and in that case I had the router.navigate method which I can't find a direct equivalent for.

As a result of doing the above the URL is updated and the route is run, so I've got what I want, but it feels a bit unwieldy. Is there a better way of doing this?

Upvotes: 0

Views: 2300

Answers (2)

tim99
tim99

Reputation: 65

You can setup a route for specified links, and Sammy should route automatically to the route-event when clicking these links. In the route you can load content via ajax or redirect to another page. A small example:

HTML:

<section id="navi"> 
  <a href="#/1">One</a>
  <a href="#/2">Two</a>
  <a href="#/3">Three</a>
</section>

JS:

;(function($) {
  var app = $.sammy(function() {
    this.get('#/:page', function() {
      var jmnu = $( 'a[href="#/' + this.params['page'] + '"]' );
      // do whatever you want to do before pageload
      // even trigger click events manual

      // and then load page:
      $('#main').html('<p>this is site ' + this.params['page'] + '</p>');
    });
 });

  $(function() {
    app.run('#/1')
  });
})(jQuery);

see demo: http://jsfiddle.net/0qpx7dob/

Upvotes: 0

jcd.no
jcd.no

Reputation: 55

app.setLocation('#/YourPathHere');

or

window.location = '#/YourPathHere';

From documentation:

Sammy.Application setLocation ( new_location ) Delegates to the location_proxy to set the current location. See Sammy.DefaultLocationProxy for more info on location proxies. Arguments

new_location A new location string (e.g. '#/')

http://sammyjs.org/docs/api/master/Sammy.Application.methods.setLocation

Upvotes: 1

Related Questions