KnockoutJs Components with RequireJs and TypeScript

When configuring components in the documentation for knockouts, I see:

define(['knockout', 'text!./my-component.html'], function (ko, htmlString) {
    function MyComponentViewModel(params) {
        // Set up properties, etc.
    }

    // Return component definition
    return { viewModel: MyComponentViewModel, template: htmlString };
});

I use TypeScript in my project. How to convert the previous code to TypeScript?

I tried this:

import ko = require("knockout");
import htmlString = require("text!./my-component.html");

class MyComponentViewModel {
}

But what about instructions return?

return { viewModel: MyComponentViewModel, template: htmlString };
+4
source share
1 answer

I am using the following configuration (this seems to be a bit overloaded, but I hope this helps):

"index.ts", configures require.js:

require.config({
    baseUrl: 'Scripts',

    paths: {
        //main libraries
        jquery: '../Scripts/jquery-2.1.3',
        knockout: '../Scripts/knockout-3.2.0.debug',

        //shortcut paths
        components: '../components',
        modules: '../modules'
    },

    shim: {
        jquery: {
            exports: '$'
        }
    }
});

// ...... cutted
// here goes app entry point code

"application.ts" from the "modules" folder contains the component registration code:

import ko = require("knockout");

ko.components.register('like-widget', {
    viewModel: { require: 'components/like-widget' },
    template: { require: 'text!components/like-widget.html' }
});

"like-widget.ts" from the "components" folder, component presentation model:

import ko = require("knockout");

class LikeWidgetViewModel {
    constructor(params: { value: KnockoutObservable<string> }) {
        this.chosenValue = params.value || ko.observable<string>();
    }

    chosenValue: KnockoutObservable<string>;

    like() {
        this.chosenValue('like');
    }
    dislike() {
        this.chosenValue('dislike');
    }
}

export = LikeWidgetViewModel;

"like-widget.html" "components":

<div class="like-or-dislike" data-bind="visible: !chosenValue()">
    <button data-bind="click: like">Like it</button>
    <button data-bind="click: dislike">Dislike it</button>
</div>

<div class="result" data-bind="visible: chosenValue">
    You <strong data-bind="text: chosenValue"></strong> it.
    And this was loaded from an external file.
</div>
+2

Source: https://habr.com/ru/post/1628942/


All Articles