5

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.

4

1 回答 1

2

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

好吧,我回到小提琴并清理了所有代码,以有效地向您展示我的回答的意思-

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());

请记住,尽管在小提琴中我不能真正使用 Sammy.js(我没有更改视图或导航)并且基本上没有理由使用 Require.js,因为它只是一个示例,我放置了所有视图模型在同一个 JS 文件中。

由于您使用的是 Sammy 和 Require,您需要获取此代码并将其在功能上应用到您的站点,或者在某处发布更多代码。

于 2013-07-21T15:14:42.383 回答