简体   繁体   English

使用敲除JS时出现错误

[英]error when working with knockoutJS visible

I work with knockoutJS and I have an error when I want close a block div or h html tag. 我使用基因敲除JS,当我想关闭一个块divh html标签时遇到错误。 My Javascript code where the error occurs: 错误发生的我的Javascript代码:

function myModel(){
this.flags = false;
    this.getFlag = ko.computed(function(){
        if(this.flags == false){
            this.flags = true;
        }else{
            this.flags = false;
        }
        console.log(this.flags);
        return this.flags;
    });
}
ko.applyBindings(new myModel());

My HTML: 我的HTML:

<button data-bind="click: getFlag">Click button</button>
<h3 data-bind="visible: getFlag()">test visible</h3>

When I click my button I have this message in the browser console: 当我单击按钮时,在浏览器控制台中显示以下消息:

false Uncaught Error: Cannot write a value to a ko.computed unless you specify a 'write' option. false未捕获的错误:除非您指定“写入”选项,否则无法将值写入ko.computed。 If you wish to read the current value, don't pass any parameters.knockout-3.3.0.js:44 gknockout-3.3.0.js:83 (anonymous function) 如果您希望读取当前值,请不要传递任何参数。knockout-3.3.0.js:44 gknockout-3.3.0.js:83(匿名函数)

When I write my javascript code without function ko.computed() 当我写没有功能ko.computed() javascript代码时

    this.flags = false;
    this.getFlag = function(){
        if(this.flags == false){
            this.flags = true;
        }else{
            this.flags = false;
        }
        console.log(this.flags);   
        return this.flags;
    };

I have this message in browser console: 我在浏览器控制台中有以下消息:

true 真正

When I press the button I have false , and etc true false true false but visible doesn't work. 当我按下按钮时,我有false ,等等true false true falsevisible不起作用。 What is the problem? 问题是什么?

So first you need to declare your properties as observable: 因此,首先您需要将属性声明为可观察的:

var self = this;
self.flag = ko.observable(false);

Next we'll make a toggle to switch the flag back and forth: 接下来,我们将进行切换来回切换标记:

self.toggleFlag = function(){
   self.flag(!self.flag());
}

Now you can bind: 现在您可以绑定:

<button data-bind="click: toggleFlag">Click button</button>
<h3 data-bind="visible: flag">test visible</h3>

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

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