【问题标题】:Use a knockout component without the view model .JS file?使用没有视图模型 .JS 文件的淘汰组件?
【发布时间】:2015-11-04 22:56:59
【问题描述】:

我正在尝试创建一个剔除组件并从如下文件加载其模板:

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 能够从任何其他视图模型中调用其他视图模型函数,并且可能将 ordersViewModel 分离到另一个文件中会使事情变得更加困难。

【问题讨论】:

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


    【解决方案1】:

    完全可以,你可以单独指定组件的viewModel和模板。

    在您的情况下,问题是您在模板路径之前缺少text!,因此 RequireJs 尝试将其作为 javascript 资源加载。

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

    【讨论】:

    • template: {require: 'text!../views/orders/compactTable.html'}, 也不起作用。它试图获取GET https://localhost/text.js Uncaught Error: Script error for: text
    • 您使用的是哪个模块加载器?我假设你使用 require.js
    • 我正在使用 require.js 是的。刚刚在我的页面标题中添加了require.js,位于主 javascript 文件之前。
    【解决方案2】:
    //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>'
                }
    
            });
        })();
      }    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-10
      • 2015-05-28
      • 2014-10-20
      • 1970-01-01
      • 2014-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多