Question

I'm just getting started with Sammy and Knockout. I've defined a simple array of pages/routes within my view model as well as my routes:

(function($) {
    function ViewModel() {
        var self = this;
        self.chosenRoute = ko.observable();
        self.viewData = ko.observable();

        self.pages = [
            {'title': 'Home', 'route': '#/'},
            {'title': 'Job Candidates', 'route': '#/job-candidates'},
            ...
        ];

        self.goToPage = function(page) {
            location.hash = page.route;
        };

        Sammy(function() {
            this.use('Title');
            this.setTitle('Vintage Services');  // Doesn't work

            this.get('#/', function(context) {
                self.chosenRoute('#/');
                context.render('/static/templates/home.html', null,
                    self.viewData);
                window.document.title = 'Vintage Services'; // Works
            });

            this.get('', function() {
                this.app.runRoute('get', '#/');
            });
        }).run();
    }

    ko.applyBindings(new ViewModel());
})(jQuery);

I've included the Sammy Title plugin in my template, and I'm not getting any errors, but the plugin won't set the title. If I use window.document.title, it works. Can anyone see what I'm doing wrong?

Was it helpful?

Solution

The Title plugin comes with two method:

setTitle allows setting a global title or a function that modifies the title for each route/page.

So in itself it does not set the page title, you need to use the the plugin second method:

Helper title() sets the document title, passing it through the function defined by setTitle() if set.

So to actual modify the title you need to use the title helper inside your routes:

 this.get('', function() {
            this.title('Vintage Services');
            this.app.runRoute('get', '#/');
        });

Or if you want to have always 'Vintage Services' in the title you can use the setTitle like before

this.setTitle('Vintage Services'); //so this call does not set the title

this.get('', function() {
    this.title(); // this call sets the title to 'Vintage Services'
    //this.title('Main'); //this call sets the title to 'Vintage Services Main'
    this.app.runRoute('get', '#/');
});

Note: If your are using the official Sammy plugins the this.use('Title'); and this.use(Sammy.Title); calls are equivalent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top