Pass custom parameters into Typedscript-defined Knockout component loaded as AMD using requirejs

时间:2016-04-25 09:16:04

标签: knockout.js typescript requirejs

I have built a dashboard component that loads other components using the knockout component binding. Using Typescript. Basically it works.

The components are registered as follows ...

ko.components.register('camera-widget', {
    viewModel: { require: 'Scripts/app/Widgets/CameraWidget/ViewModels/CameraWidgetViewModel' },
    template: { require: 'text!Scripts/App/Widgets/CameraWidget/Views/CameraWidget.html' }
});

... and instantiated cusing the component binding (where tagName = 'camera-widget' and parameters = { /* some initial values to have the component load its data */ }) :

<div data-bind="component: tagName, params: parameters"></div>

In Typescript the CameraWidgetViewModel class is defined as follows:

import ko = require('knockout');
import PagerSettings = require('../Models/PagerSettings');
import PagerSettingsViewModel = require('./PagerSettingsViewModel');
import CameraViewModel = require('./CameraViewModel');

class CameraWidgetViewModel implements CameraWidget.ICameraWidgetViewModel {
    constructor (data: any) {
         if (data.someValue) {
             // BOOOOM! data is undefined
         }
    }
}
export = CameraWidgetViewModel;

Compiled into JS the CameraWidgetViewModel class is wrapped in an anonymous function:

define(["require", "exports", 'knockout', '../Models/PagerSettings', './PagerSettingsViewModel'], function (require, exports, ko, PagerSettings, PagerSettingsViewModel) {
    var CameraWidgetViewModel = (function () {
        function CameraWidgetViewModel(data) {
        }
    });
});

How can I manage the parameters from the component binding to be passed into that inner function call?

2 个答案:

答案 0 :(得分:1)

在关于组件绑定的淘汰赛文档中,您可以找到所需的语法:

  

要向组件提供参数,请使用以下属性传递对象

     
      
  • name - 要注入的组件的名称。再次,这是可以观察到的。

  •   
  • params - 将传递给组件的对象。通常,这是一个包含多个参数的键值对象,通常由组件的viewmodel构造函数接收。

  •   

来源:Knockout Component Binding, subheading: API,强调我的

您实例化绑定的方式传递了component绑定之外的参数。它们应该位于params属性后面的对象中。您必须使用此标记:

data-bind="component: { name: tagName, params: parameters }"

答案 1 :(得分:0)

You aren't exporting anything from your CameraWidgetViewModel file so nothing is actually being defined. But I also don't think you're supposed to be exporting a class because it looks like knockout expects a function to be returned, not a constructor.

I would try adding this to the bottom of your file:

function getViewModel(...args) {
  return new CameraWidgetViewModel(...args);
}

export = getViewModel;