knockout.js - 使用 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>
解决方案
您遇到了问题,因为您将 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>
推荐阅读
- swift - 无论我使用什么类型,都会出现“类型不匹配”
- javascript - 在数据范围内未找到日期
- django - Django geoip2 + Maxmind 在本地工作,但不在生产中?
- plot - Netlogo 如何制作有序直方图
- python - 如何仅将此网站 HTML 表的第一列和 href 链接刮到 pandas 数据框中?
- c# - 如何将自定义测试框架与 IDE 集成?
- python - 找到与给定数字的和最接近的一对元组
- docker - docker-compose 构建语言切换后不起作用
- python - 通过 3D 网格绘制抛物线的算法
- django - 如何通过外键从与另一个模型相关的模型中检索特定对象?