使用Knockout从元素获取有界属性

时间:2019-06-27 11:25:13

标签: knockout.js

我有一个绑定到viewModel的元素

 Save(add: NgForm)
 {

  let formvalue=JSON.parse(localStorage.getItem('datasource'));
  let data=JSON.parse(localStorage.getItem('data'));
     this.addservice.add(data).subscribe(res=>{
       if(res){
        this.addservice.add(formvalue);
       }})

   this.objadd=new Data();
   this.objadd.description=formadd.value.name;
   this.addservice.add(this.objadd).subscribe(res=>{
     if(res){
   // this.addservice.add(this.formadd.value)
   }});    
  this.addservice.add(formvalue + this.formadd.value);
 }

稍后,在脚本中,我需要设置绑定到元素的属性。我有这样的脚本;

<input id="myId" data-bind="text: myProperty"></input>

2 个答案:

答案 0 :(得分:1)

您遇到了问题,因为您将jQuery方法与淘汰赛混合使用。使用基因剔除的一般规则是:

  • 使用双向绑定而不是事件侦听器
  • 在真正需要时,使用event绑定进行事件处理
  • 仅通过数据绑定触摸DOM

如果您绝对希望继续朝着您选择的方向发展,则可以重新评估data-bind属性,以找出绑定到text的属性(不推荐)。

ko.applyBindings({ myProperty: ko.observable("Initial text") });


const h1 = document.querySelector("h1");
const bindingString = h1.getAttribute("data-bind");
const bindingObject = ko.expressionRewriting.parseObjectLiteral(bindingString);
const textBinding = bindingObject.find(({ key }) => key === "text");

if (textBinding) {
  const vm = ko.dataFor(h1);
  const obsProp = vm[textBinding.value];
  
  obsProp("Hello world")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<h1 data-bind="text: myProperty"></h1>  

但是,我会做这样的事情:

const hasFocus = ko.observable(false);
const label = ko.pureComputed(
  () => hasFocus() ? "Hello world" : "Initial text"
);

ko.applyBindings({ hasFocus, label })
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<label>
  <span data-bind="text: label"></span>
  <input data-bind="hasFocus: hasFocus" placeholder="focus on me to see something happen!">
</label>

答案 1 :(得分:0)

除其他外,您可以直接在淘汰赛中绑定focusout事件:

var ViewModel = function() {
  var self = this;
  self.myProperty = ko.observable("my text");
  self.onfocus = function(data, event) {
    // do something on focus
    var currText = self.myProperty.peek();
  };
  self.onfocusout = function(data, event) {
    // do something on focusout (or blur)
    var currText = self.myProperty.peek();
    var newText = currText.split("").reverse().join("");
    self.myProperty(newText);
  };
};

$(document).ready(function() {
  ko.applyBindings(new ViewModel());
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
</head>

<body>
  <div>
    <div>
      <input type="text" id="myId" data-bind="value: myProperty, event: {focus: onfocus, focusout: onfocusout }">
      <hr/>
      <pre data-bind="text:ko.toJSON($data)"></pre>
    </div>

  </div>
</body>

</html>