Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'}
like image 577
mehrandvd Avatar asked Dec 06 '25 20:12

mehrandvd


1 Answers

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.

like image 76
Matthew James Davis Avatar answered Dec 08 '25 10:12

Matthew James Davis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!