Knockout没有使用值绑定提供更新的值

时间:2017-04-02 04:21:47

标签: knockout.js console.log

我想使用knockout在控制台中打印输入元素的值。

当我尝试打印该值时,我得到“结果”而不是文本框的值。

var ViewModel = {
   name: ko.observable("name"),
   company: ko.observable("company"),
   submit: ko.observable("Submit"),
   onsubmit: function(){
      console.log(name);
   }
}

ko.applyBindings(ViewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<form>
   <label>Name</label>
   <input type="text" data-bind="value:name"/>
   <label>Company</label>
   <input type="text" data-bind="value:company"/>
   <button data-bind="click:onsubmit,text:submit"></button>
</form>

1 个答案:

答案 0 :(得分:1)

您也可以这样做。我想为我的viewmodel声明一个函数,以便以后可以用来初始化另一个新对象。

&#13;
&#13;
var ViewModel = function() {
  var self = this;
  self.name = ko.observable("name");
  self.company = ko.observable("company");
  self.submit = ko.observable("Submit");
  self.onsubmit = function(){
   alert(self.name())
   console.log(self.name());
  };
}
ko.applyBindings(new ViewModel());
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<label>Name</label>
<input type="text" data-bind="value: name"/>
<label>Company</label>
<input type="text" data-bind="value: company"/>
<button data-bind="click: onsubmit, text: submit"></button>
&#13;
&#13;
&#13;