使用ko.mapping.fromJS映射对象数据以查看模型函数

时间:2016-01-26 21:10:10

标签: javascript knockout.js

我创建了一个knockout js组件,如下所示:

define(['knockout', 'text!./details.html'], function(ko, htmlString) {

    function detailsViewModel(params) {
        var response = getDummyResponse();
        // how to extend the view model with ko.mapping.fromJS()?
    }

    function getDummyResponse(){
        return {
            foo: 1,
            bar: 2
        };
    }

    return { viewModel: detailsViewModel, template: htmlString };
});

返回的视图模型需要是构造函数才能成为有效的挖空组件。

让我们假设getDummyResponse()返回一个我希望扩展我的视图模型的大对象,使用ko.mapping.fromJS来映射数据。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您需要指定构造函数的假设不正确。还有其他options。我建议你的情况是View Model工厂。

来自the relevant docs

  

如果要在绑定到viewmodel之前在关联元素上运行任何设置逻辑,或者使用任意逻辑来决定实例化哪个viewmodel类:

   ko.components.register('my-component', {
       viewModel: {
           createViewModel: function(params, componentInfo) {
               // - 'params' is an object whose key/value pairs are the parameters
               //   passed from the component binding or custom element
               // - 'componentInfo.element' is the element the component is being
               //   injected into. When createViewModel is called, the template has
               //   already been injected into this element, but isn't yet bound.
               // - 'componentInfo.templateNodes' is an array containing any DOM
               //   nodes that have been supplied to the component. See below.

               // Return the desired view model instance, e.g.:
               return new MyViewModel(params);
           }
       },
       template: ...
   });

在工厂方法中,如果您愿意,可以使用ko.mapping