Search code examples
javascriptjqueryknockout.jsknockout-2.0

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

{view:'dummy.html',model:'dummymodel'}.

I tried obvar(""); but its not happening. obvar =""; would convert it to normal string. How to empty the contents?


Solution

  • 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.

    Your requirement that you mention is (emphasis mine):

    ...I want to empty the contents, if variable obvar contains {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).

    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>