Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout, Require, Sammy and a view model for each page – how do I make it work?

I have a KO app and each of my pages has a separate view model that handles all the actions required on that page (load, add, edit, delete, etc). I've managed to split the code up into multiple modules using RequireJS, but I can't find a way for multiple view models to work at once using Sammy.

This is the setup I have in my init.js file at the moment, which loads the content on the first page. And it works:

require(['jquery', 'ko', 'sammy', 'viewmodels/page1'], function($, ko, sammy, page1) {
  var page1VM = new page1.ViewModel();
  ko.applyBindings(page1VM);

  var app = sammy('#wrapper', function() {
    this.get('#page1', function() {
      page1VM.loadContent();
    });

    this.get('#page2', function() {
      // do nothing yet
    });

    [...]

    this.get('#pageX', function() {
      // do nothing yet
    });
  });

  app.run('#page1');
});

How can I bind my other view models to the other pages?

I also tried adding a separate ko.applyBindings for each page inside this.get, which threw an error when I switched back to a page that had already applied those bindings.

like image 720
Norbert Avatar asked Nov 02 '22 18:11

Norbert


1 Answers

http://jsfiddle.net/PgLgz/4/

Alright I went back into fiddle and cleaned all the code up to show you effectively what I meant by my answer -

function myViewModel() {
    var self = this;
    self.message = "hey";
    self.page1VM = new page1VM();
    self.page2VM = new page2VM();
    var app = sammy('#wrapper', function() {
        this.get('#page1', function() {
            page1VM .loadContent();
        });
    });
};

ko.applyBindings(new myViewModel());

Remember though that in the fiddle I can't really utilize Sammy.js (I am not changing views or navigating) and there is essentially no reason to use Require.js since it is just an example, and I put all of the view models in the same JS file.

Since you are using Sammy and Require you will need to either take this code and functionally apply it to your site or post a larger bit of code somewhere.

like image 182
PW Kad Avatar answered Nov 09 '22 14:11

PW Kad