2016-09-27 68 views
-3

我被卡住在通过knockout.js的ko.toJSON收集json数据。有几个可观察的变量,当用户键入一些字符串时,我可以收集一些输入字段,但用户单击按钮时无法获得按钮状态。ko.toJSON不接受更新的可观察值

的html代码:

<input type="text" name="port_name" 
    class="form-control" 
     data-bind="value: portName" 
     placeholder="Enter name of port" /> 
<span class="input-group-btn"> 
    <button class="btn btn-switch" 
      data-bind="css: btnStatus" 
      data-toggle="button" 
      data-bind="aria-pressed: btnIsPressed" 
      autocomplete="off"> 
    <i class="fa" data-bind="css: btnName"></i> 
    </button> 
</span> 

如果用户写东西“port_name中指”字段,然后单击按钮,然后提交整个表单,通过使用ko.toJSON(viewmodel)我可以得到JSON字符串,其中portName为写什么用户,但按钮像“btnIsPressed”这样的状态永远不会改变,只是保持初始值。也尝试添加点击功能强制值,但它并不能帮助......

$(function() //click funcion for Port Enable buttons 
{ 
}).on('click', '.btn-switch', function(e) { 
    if (this.getAttribute("aria-pressed") == true) { 
    this.setAttribute("aria-pressed", false); 
    console.log(this.getAttribute("aria-pressed")); 
    } else { 
    this.setAttribute("aria-pressed", false); 
    console.log(this.getAttribute("aria-pressed")); 
    } 
}); 

从控制台我可以看到“咏叹调压”值切换,但ko.toJSON结果总是初始值。我错过了什么?谢谢。

视图模型如下:

//PortViewModel 
function Port(_port_id, 
       _port_is_enabled, 
       _max_number_of_ports_per_module, 
       _id_of_last_port) { 
    this.portId = ko.observable(_port_id); 
    var portStatus = _port_is_enabled; 
    this.portName = ko.observable("No Name");//_port_name; 

    this.btnStatus = ko.pureComputed(function() { 
     return (_port_is_enabled) ? 
       "btn-success" : "active btn-danger"; 
    }); 

    this.btnIsPressed = ko.observable(_port_is_enabled); 

    this.btnName = ko.pureComputed(function() { 
     return (_port_is_enabled) ? "fa-play" : "fa-stop"; 
    }); 
} 
+0

请显示您的型号代码。 –

+0

不仅仅是“btnIsPressed”,除了“portName”之外,其他观察值不会更新每个用户的操作。 – cheart

+1

为什么你有两个单独的'数据绑定'按钮?你有'咏叹调按'的自定义绑定? –

回答