首页 > 解决方案 > 使用 Knockout 从元素获取有界属性

问题描述

我有一个绑定到 viewModel 的元素

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

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

<script>
    //mySelector can be any element in our current case it will be "#myId"
    //focusout is just the event that triggers the action, it could be others also
    $(mySelector).focusout(function (){
       var observable = ko.dataFor(this);
       var context = ko.contextFor(this);

       // I could do
       observable.myProperty('Some Value');
       //but it could be anything, I need to retrieve the property from mySelector
       //how can this be done?

    });
</script>

标签: knockout.js

解决方案


您遇到了问题,因为您将 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>


推荐阅读