如何访问Knockout组件功能

时间:2015-11-07 11:31:42

标签: javascript knockout.js

我开始在Knockout Component的工作中转换系统的一部分,但是任何时候,我都需要在我的组件中定义的访问函数。

示例我将创建msgComponent

在Html中:

<body>
    <msgComponent params="message: 'blablabla'"></msgComponent>
</body>

在Js:

ko.components.register('msgComponent', {
    viewModel: function (params)
    {
        this.message = ko.observable(params.message);

        this.showMessage = function()
        {
            alert(this.messenge());
        }.bind(this);
    },
    template: '<div data-bind="text: message"></div>'
});


function myMasterViewModel()
{
    var master = this;

    // How to can I access my component this way?
    master.msgComponent = msgComponent;

    master.showMessage();
}

在我的示例中,如何使用其他视图模型访问我的组件功能?

拳头编辑: @花花公子 如果我在页面中需要更多msgComponent实例,我可以这样定义吗?

var sharedComponent = function(params){
    var params = params || {};
    this.message = ko.observable(params.message);
    this.showMessage = function()
    {
        alert(this.message());
    }.bind(this);
}

ko.components.register('msgcomponent', {
    viewModel: function(params)
    {
        this.instance = params.viewModel;
    },
    template: '<div data-bind="with: instance"><div data-bind="text: message"></div></div>'
});

function myMasterViewModel()
{
    var master = this;

    master.msg = new sharedComponent({message: 'huahua'});

    master.show = function()
    {
        master.msg.showMessage();
    };
}

或者对这种情况有更正确的方法吗?

1 个答案:

答案 0 :(得分:1)

您可以尝试instance组件注册方法。像

这样的东西
var sharedComponent = function(params){
  var params = params || {};
  this.message = ko.observable(params.message);
  this.showMessage = function()
  {
      alert(this.message());
  }.bind(this);
}

var comShared = new sharedComponent ({message: 'test mssage'});

ko.components.register('msgcomponent', {
    viewModel: {instance: comShared },
    template: '<div data-bind="text: message"></div>'
});

function myMasterViewModel()
{
    var master = this;

    // How to can I access my component this way?
    master.msgComponent = comShared;
    master.msgComponent.showMessage();
}

了解更多here