2

I'm trying to create a knockout component and load its template from a file like so:

function ordersViewModel(){
   //whatever
}

function equipmentViewModel(){
   //whatever
}

ko.components.register('compact-view', {
    viewModel: ordersViewModel,
    template: {require: '../views/orders/compactTable.html'},
    synchronous: true
});

var MasterModel = function(){
    this.orders = new ordersViewModel(),
    this.equipment = new equipmentViewModel();
};

var mm = new MasterModel();

And I'm getting the following error:

Failed to load resource: the server responded with a status of 404 (Not Found) https://localhost/views/orders/compactTable.html.js

It seems it is looking for the .js as detailed in the docs:

For this to work, the files files/component-like-widget.js and files/component-like-widget.html need to exist.

Isn't there a way to use a component without having to separate the viewmodel in another file?

I'm using a MasterModel to be able to call other viewmodel functions from any other viewmodel, and probably separating the ordersViewModel in another file will make things more difficult.

Andrea Casaccia
  • 4,802
  • 4
  • 29
  • 54
Alvaro
  • 40,778
  • 30
  • 164
  • 336

2 Answers2

3

It's definetely possible to do it, you can separately specify the viewModel and the template for a component.

In your case the problem is that you are missing text! before the template path and so RequireJs tries to load it as a javascript resource.

Also, you need to include the RequireJs text plugin: https://github.com/requirejs/text

Andrea Casaccia
  • 4,802
  • 4
  • 29
  • 54
  • `template: {require: 'text!../views/orders/compactTable.html'},` is not working either. It tries to get `GET https://localhost/text.js `. `Uncaught Error: Script error for: text` – Alvaro Aug 12 '15 at 11:16
  • 1
    Which module loader are you using? I am assuming you use require.js – Andrea Casaccia Aug 12 '15 at 11:18
  • I am using require.js yeah. Just added the `require.js` in my page header before the main javascript file. – Alvaro Aug 12 '15 at 11:20
0
//Component with no viewmodel
namespace Components {

export namespace NoViewModelComponent{

    export const componentName = 'no-viewmodel-component';

   //No Viewmodel as is taken care of elsewhere
    (function register() {
        ko.components.register(componentName, {
            template: {
             //using require
              require: 'text!' + BASE_URL + 'Views/Components/NoViewModelView.html'
             //OR direct html
             //'<div > {{My Var}}</div>'
            }

        });
    })();
  }    
}
Traci
  • 908
  • 1
  • 13
  • 31