简体   繁体   English

data-bind =“click”不使用嵌套的knockout视图模型

[英]data-bind=“click” not working with nested knockout view model

I have a knockout view model that is set up as an observable as my main view model. 我有一个淘汰视图模型,它被设置为一个可观察的主视图模型。 In the child element, it seems that I can't set up data-bind="click: the same way that I can when I am in the parent element. 在子元素中,似乎我无法设置data-bind="click:就像我在父元素中一样。

My html: 我的HTML:

 <button id="myButton" type="button" class="btn btn-lg btn-primary" data-bind="click: test">Click Me</button>

In my main view model: 在我的主视图模型中:

 self.childElement = ko.observable(new childElementVm());

and in childElementVm 并在childElementVm

var childElementVm= function () {
    var test = function(){
        alert('this is a test');
    }
}

what do I need to do differently to use data-bind="click: test" here? 在这里使用data-bind="click: test"我需要做些什么? To note, my applyBindings is fine (other knockout observables are functioning correctly) and the button is contained inside of a <div data-bind="with: childElement" 要注意,我的applyBindings很好(其他的knockout observable正常运行),按钮包含在<div data-bind="with: childElement"

EDIT: here is a fiddle 编辑: 这是一个小提琴

Your test function is scoped to the childElementVm only. 您的test函数仅限于childElementVm Change your implementation to this: 将您的实现更改为:

var childElementVm= function () {
    this.test = function(){
        alert('this is a test');
    }
}

or this: 或这个:

var childElementVm= function () {
    var self = this;
    self.test = function(){
        alert('this is a test');
    }
}

Here is a working example 这是一个有效的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM