Search code examples
javascriptrequirejssingle-page-applicationdurandalhottowel

Static module declaration using Durandal and Require


I'm using Durandal and Require for my SPA application. Also I'm using HotTowel template from John Papa.

For my modules, I need some of them to be created per request and some of them to be singleton.

define([], function(){
    var bookId = ko.observable();
    var bookName = ko.observable();

    return {
        bookId: bookId,
        bookName: bookName
    };
}

The above module seems to return a new instance for each composition use like:

compose: {model: 'viewmodels/book'}

But what if I want the view model to be same in all compositions. For example I want a viewmodel for my login named loginInfo which will be used in lots of places, so it shouldn't initialize on each composition as it was initiated somewhere at first login.

compose: {model: 'viewmodels/loginInfo'}

Solution

  • In Durandal, if a viewmodel returns an object

    define(function(require) {
        return { a: 1, b: 2 }
    });
    

    Durandal will persist the same object. If a viewmodel returns a constructor

    define(function(require) {
        return Function() {
            this.a = 1;
            this.b = 2;
        }
    });
    

    Durandal will create a new object by invoking the constructor.