[英]Making a observable variable as null
I have a an observable variable of the following format: 我有一个以下格式的可观察变量:
var obvar = ko.observable("");
obvar({view:'dummy.html',model:'dummymodel'});
In one of my checks I want to empty the contents , if variable "obvar" contains 在我的一个检查中,我想清空内容,如果变量“obvar”包含
{view:'dummy.html',model:'dummymodel'}.
I tried obvar("");
我试过
obvar("");
but its not happening. 但它没有发生。
obvar ="";
would convert it to normal string. 将它转换为普通字符串。 How to empty the contents?
如何清空内容?
Your first code snippet: 您的第一个代码段:
var obvar = ko.observable(""); obvar({view:'dummy.html',model:'dummymodel'});
has a special but important feature. 有一个特殊但重要的特征。 The
obvar
observable first contains a string
, and after the second line it contains an Object
. obvar
observable首先包含一个string
,在第二行之后它包含一个Object
。
Your requirement that you mention is (emphasis mine): 您提到的要求是(强调我的):
...I want to empty the contents , if variable
obvar
contains{view:'dummy.html',model:'dummymodel'}
...如果变量
obvar
包含{view:'dummy.html',model:'dummymodel'}
我想清空内容
It's unclear to me what you mean by "empty" the contents, and perhaps to you as well (since you've tried obvar("");
, which in a sense "empties" the content, but it had not the desired result). 我不清楚你的意思是“清空”内容,也许也是你的意思(因为你已经尝试过
obvar("");
这在某种意义上说“清空”内容,但它没有达到预期的结果)。
At any rate, here are two ways to do it, in a runnable snippet so you can see proof that it's working: 无论如何,这里有两种方法,在一个可运行的片段中,你可以看到它正在工作的证据:
function ViewModel() { var self = this; var obvar = ko.observable(""); obvar({view:'dummy.html',model:'dummymodel'}); self.obvar = obvar; // Expose it so the view can demo the workings. function canEmptyContents() { // empty the contents if variable "obvar" contains {view:'dummy.html',model:'dummymodel'} return obvar().view === 'dummy.html' && obvar().model === 'dummymodel'; } self.option1 = function() { if (canEmptyContents()) { obvar(""); } }; self.option2 = function() { if (canEmptyContents()) { obvar({ dummy: "", model: "" }); } }; } ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script> <button data-bind="click: option1">Option 1: empty with string</button> <button data-bind="click: option2">Option 2: empty with empty object</button> <hr> Debug info: <pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.