Knockout - 当绑定值更改时元素上会触发什么?
我试图了解当 Knockout 由于 applyBinding 更新其中的值时,它会对页面上的元素执行什么操作。
考虑这个简单的例子:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script src="../lib/jquery-1.7.1.min.js"></script>
<script src="../lib/knockout-2.0.0.js"></script>
<script>
$(function () {
$("#itemNumber").change(function() {
console.log('itemNumber');
});
//create The view Model
var product1 = {
id: 1002,
itemNumber: "T110",
model: "Taylor 110",
salePrice: 699.75
};
ko.applyBindings(product1);
});
</script>
</head>
<body >
<input data-bind="value: itemNumber" type="text" id="itemNumber" />
</body>
</html>
当我运行页面 T110 时,它出现在我的输入框中,当我更改值时,控制台消息将按我的预期显示。
但请注意,正如我所期望的那样,在页面加载期间调用 applyBindings 时它不会触发...
那么它使用什么机制来修改输入元素的值?我真正正在寻找的是某种方法来检测元素本身中的这一点,因为这是一个控件,我想将真实值从隐藏字段复制到正确的位置,但保留粘在其上的任何值...
谢谢
I am trying to understand what Knockout does to elements on the page when it updates the values in them due to applyBinding.
Consider this simple example:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script src="../lib/jquery-1.7.1.min.js"></script>
<script src="../lib/knockout-2.0.0.js"></script>
<script>
$(function () {
$("#itemNumber").change(function() {
console.log('itemNumber');
});
//create The view Model
var product1 = {
id: 1002,
itemNumber: "T110",
model: "Taylor 110",
salePrice: 699.75
};
ko.applyBindings(product1);
});
</script>
</head>
<body >
<input data-bind="value: itemNumber" type="text" id="itemNumber" />
</body>
</html>
When i run the page T110 appears in my input box and when i change the value the console message is shown as i expect.
But notice it does not fire when applyBindings is called during the page load as I would expect...
So what mechanism does it use to modify the input element's value? And what i am really looking for is some way to detect this in the element itself as this is a control and I would like to copy the real value from a hidden field to the right place but maintain any values stuck to it...
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以亲自查看源代码对于值绑定。
处理更改的默认事件是 change 事件,但它是可配置的。
另外,学习 KnockoutJs 的一个好方法是阅读教程。
You can see for yourself, reading the source for the value binding.
The default event for handling changes is the change event but that is configurable.
Also, a great way to learn KnockoutJs is to go through the tutorials.
如果不使用change事件有作用吗?
尝试手动订阅以查看效果:
Does it work if you don't use the change event?
Try manually subscribing to see the effects instead: