knockout component widget template requirejs html

2019-06-10 01:09发布

问题:

im implementing the widget example for knockout http://knockoutjs.com/documentation/component-overview.html

loading template from external html with requirejs not working for me

ko.components.register('like-or-dislike', {
template: { require: 'text!files/component-like-widget.html' }

});

i put the html containing the template in external html. replace "files/" with my relative path "/views/_leyout" and it's not working i need a text.js file that loads the html? any example ?

回答1:

The answer of user3144678 is correct. You should include text plugin inside your project. Just for clarify how to use it I did some simple project:

project structure:

project
|-- index.html
|-- app.js
`-- content
    `-- some-content.html

index.html:

<html>
    <head>
    </head>
    <body>
        <script data-main="app.js"src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js"></script>
   </body>
</html>

app.js:

requirejs.config({
    paths: {
        "text": "http://cdnjs.cloudflare.com/ajax/libs/require-text/2.0.12/text"
    }
});
requirejs(["text!content/some-text.html"], function (text) {
   alert(text);
});    

some-content.html:

<div>just some text</div>

the result will be alert with "just some text" inside.



回答2:

"text.js" is a plugin wich you can download from the require-homepage. For me, the best way to do the config for knockout-components is the following:

config.js

define(['ko'], function (ko) {

    ko.components.register('component-name', { require: 'components/viewmodels/component-name' });

});

component-name.js

define(['ko', 'text!components/templates/component-name.html'],function (ko, template) {

    var vm = function (params) {

    };

    return {
        viewModel: vm,
        template: template
    };

});

Hope it helps :)