knockoutjs在运行时更改绑定

时间:2017-04-26 05:22:24

标签: jquery knockout.js data-binding

请用这个简单的代码来说明这个案例:

    <?php

    include_once("connection.php");

    if(isset($_POST['update'])) {   
        $id = mysqli_real_escape_string($mysqli, $_POST['record_update']);
        $record_update = mysqli_real_escape_string($mysqli, $_POST['record_update']);
        $comment = mysqli_real_escape_string($mysqli, $_POST['comment']);
        $status = mysqli_real_escape_string($mysqli, $_POST['status']);
        $rt = mysqli_real_escape_string($mysqli, $_POST['rt']);
        $reason = mysqli_real_escape_string($mysqli, $_POST['reason']);
        $username = mysqli_real_escape_string($mysqli, $_POST['username']);
        $rep = mysqli_real_escape_string($mysqli, $_POST['rep']);


       if(empty($record_update)  ) {

        if(empty($record_update)) {
            echo "<script type='text/javascript'>alert('Date/Time field is blank.');window.location.href='dashboard.php';</script>";
        }


} else { 

      $result = mysqli_query($mysqli, "UPDATE employee SET record_update='$record_update', comment='$comment', status='$status', rt='$rt', reason='$reason', username='$username', rep='$rep'  WHERE id='$id'");

      if($rep->(success() == true)) {

         //do email
      } 




    }
 ?>

我想要的是通过更改下拉列表选择来改变运行时输入的属性绑定来切换语言

关于如何做到这一点的任何想法都会很棒。

这里是小提琴 https://https://jsfiddle.net/smtsghqm/2/

谢谢。

1 个答案:

答案 0 :(得分:2)

您可以尝试使用可写的计算属性,该属性根据所选选项确定要显示/更新的observable。绑定将是计算的,不必更改。

var PRDVM = function () {
    var self = this;
    self.SelectedValue = ko.observable();
    self.ID = ko.observable(0);
    self.DESCRIPTION_FR = ko.observable('FR');
    self.DESCRIPTION_EN = ko.observable('EN');
    self.IMAGE = ko.observable('/images/noimage.png');
    
    self.DESCRIPTION = ko.computed({
        read: function(){
            switch(self.SelectedValue()){
                case "0": 
          	        return self.DESCRIPTION_EN();
                case "1": 
          	        return self.DESCRIPTION_FR();
            }
        },
        write: function(value){
            switch(self.SelectedValue()){
                case "0": 
          	        self.DESCRIPTION_EN(value);
          	        break;
                case "1": 
          	        self.DESCRIPTION_FR(value);
          	        break;
            }
        }
    })
};
ko.applyBindings(new PRDVM());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<select id="se" data-bind="value: SelectedValue">
  <option value="0">EN</option>
  <option value="1">FR</option>
  <option value="2">AR</option>
  <option value="3">SP</option>
</select>
<br /><br /><br />
    <input id="inp"  data-bind='textInput: DESCRIPTION' />