删除显示值的文本绑定

Knockout text binding showing the value

本文关键字:文本 绑定 显示 删除      更新时间:2023-09-26

我正在尝试将一个元素文本绑定到一个段落标记。它工作不正常,在浏览器中没有出现任何错误。我正在使用Visual Studio进行开发。我创建了一个小提琴来显示问题,在那里我得到了一个错误,我的绑定没有定义。

    function checking(obj)
{
    var self = this;    
    self.check = ko.observable(obj.count);
    alert(self.check());
};
function MyVM()
{
    var self = this;    
    self.MyArr = ko.observableArray();        
    var myObj = {count: 4};
    self.function1 = function(){
       self.MyArr.push(new checking(myObj));        
    };
    self.function1();
}
ko.applyBindings(new MyVM(), document.getElementById('myId'));

我的HTML:

<div id = "myId">
    <p data-bind="text: check"></p>
</div>    

我知道如果我在MyVM()中定义检查字段,那么它会起作用,但我想使用来自检查(obj)的检查字段。实现这一目标的正确途径是什么。

这是链接http://jsfiddle.net/6ymx8vja/

尝试构建类似于viewModel 的视图

视图:

<div data-bind="foreach:MyArr">
    <p data-bind="text: check"></p>
</div>  

view模型:

function checking(obj)
{
    var self = this;    
    self.check = ko.observable(obj.count);
};
function MyVM()
{
    var self = this;    
    self.MyArr = ko.observableArray();        
    var myObj = {count: 4};
    self.function1 = function(){
       self.MyArr.push(new checking(myObj)); //your `check` is present inside observableArray so you need to get hold of observableArray to access its inside content      
    };
    self.function1();
}
ko.applyBindings(new MyVM());

正在处理此处

如果不想在视图中使用foreach,您可以通过索引直接访问像这个