Lazy Load Pattern with Typescript

So, with C # and other languages โ€‹โ€‹in which you have the get and set attribute by properties, it is quite simple to create a lazy loading template.

I just recently started playing with the Script type, and I'm trying to achieve something the same. I download Poco with most of its properties through Ajax Call. The problem can be described below:

export interface IDeferredObject<T> {
    HasLoaded: boolean;
    DeferredURI: string;         
}

export class Library{        

    LibraryName: string;
    Books: IDeferredObject<Book[]>;        
}   

export class Book {
    Title: string;
    UniqueNumber: number;
}



window.onload = () => {
    //Instantiate new Library
    var lib = new Library();

    //Set some properties
    lib.LibraryName = "Some Library";

    //Set the Deferred URI Rest EndPoint
    lib.Books.DeferredURI = "http://somerestendpoint";
    lib.Books.HasLoaded;      



    //Something will trigger a  GET to lib.Books which then needs to load using the Deferred Uri       

};

A couple of questions: I

  • Is an interface even the right thing to use here?
  • I would like to call the โ€œDownloadโ€ action when something accesses the Library Books property. Is it possible?

I know this is a pretty open-ended question, just looking for some recommendations on how to create this template.

thank

+4
3

Books (. TypeScript), ajax-. , , ajax, , Books. promise, . JQuery Deferred Object, $.ajax ( 1.5).

- HasLoaded DeferredURI. " ", .. Library, Library .

export class Library {
    private _loadedBooks: Book[];
    public get Books(): any {
        var result: any = null;
        // Check first if we've already loaded values from remote source and immediately resolve deferred object with a cached value as a result
        if(this.HasLoaded) {
            result = $.Deferred();
            result.resolve(this._loadedBooks);
        }
        else {
            // Initiate ajax call and when it is finished cache the value in a private field
            result = $.ajax(this.DeferredURI)
                          .done((values) => {
                              this.HasLoaded = true;
                              this._loadedBooks = values; 
                          });
        }
        return result;
   }
}

Books :

var library = new Library();
library.Books.done((books: Book[]) => {
    // do whatever you need with books collection
});

, , / Books . , - loadBooksAsync(). , , , - .

+5

?

, TypeScript

: : ?

"", - Library Books. ?

, , . TypeScript JavaScript, .

, TypeScript, module loader script bundler.

:

https://github.com/SlexAxton/yepnope.js#deprecation-notice

... yepnope , , . API , yepnope, , , , . - , , require.js, webpack, ...

. :

+1

Here is the npm module we wrote in Lossless to support lazy modules in TypeScript with flowing types: https://pushrocks.gitlab.io/smartsystem/

0
source

All Articles