使用没有视图模型.JS文件的挖空组件?

时间:2015-08-12 11:06:27

标签: javascript knockout.js requirejs knockout-3.0 knockout-3.2

我试图创建一个淘汰赛组件并从像这样的文件加载其模板:

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();

我收到以下错误:

  

无法加载资源:服务器响应状态为404(未找到)   https://localhost/views/orders/compactTable.html.js

似乎正在寻找.js详细in the docs

  

为此,文件files/component-like-widget.jsfiles/component-like-widget.html必须存在。

是否有办法使用组件而无需将视图模型与另一个文件分开?

我使用MasterModel可以从任何其他视图模型调用其他viewmodel函数,并且可能将另一个文件中的ordersViewModel分开会使事情变得更加困难。

2 个答案:

答案 0 :(得分:3)

可以明确地执行此操作,您可以单独指定viewModel和组件的模板。

在您的情况下,问题是您在模板路径之前缺少<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="product-img-loop"> <div class="reveal reveal1"> <a href="#" class="grid__image"> <img class="first-image" src="{{ product.featured_image.src | img_url: '2048x2048' }}" alt="" /> </a> <div class="hidden one"> <a href="#" class="grid__image"> <img class="last-image" src="{{ product.images.last | img_url: '1024x1024' }}" alt="" /> </a> </div> </div> <div class="reveal newreveal"> <a href="#" class="grid__image"> <img class="first-image" src="{{ product.featured_image.src | img_url: '2048x2048' }}" alt="" />first </a> <div class="hidden two"> <a href="#" class="grid__image"> <img class="last-image" src="{{ product.images.last | img_url: '1024x1024' }}" alt="" />second </a> </div> </div> <div class="reveal newreveal"> <a href="#" class="grid__image"> <img class="first-image" src="{{ product.featured_image.src | img_url: '2048x2048' }}" alt="" />first </a> <div class="hidden three"> <a href="#" class="grid__image"> <img class="last-image" src="{{ product.images.last | img_url: '1024x1024' }}" alt="" />second </a> </div> </div> </div>,因此RequireJs会尝试将其作为javascript资源加载。

此外,您还需要包含RequireJs文本插件:https://github.com/requirejs/text

答案 1 :(得分: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>'
            }

        });
    })();
  }    
}