简体   繁体   English

如何将现有DOM元素绑定到KnockoutJS viewModel

[英]How to bind existing DOM elements to a KnockoutJS viewModel

I'm using KnockoutJS to update the DOM if a JS value is changed (Knockout gives us this functions). 如果更改了JS值,我正在使用KnockoutJS来更新DOM(Knockout为我们提供了这个功能)。

A default Knockout viewModel looks something like the following block: 默认的Knockout viewModel类似于以下块:

Javascript: 使用Javascript:

var viewModel = {
    price: ko.observable(109)
}

Html: HTML:

<span data-bind="text: price"></span>

Now when the price changes, the view is automatically updated by Knockout.. But what I'd like to have is the following: 现在价格发生变化时,Knockout会自动更新视图。但我想要的是以下内容:

var viewModel = {
    price: ko.observable(jQuery("#price"))
}

<span id="price">99.00</span>

So, I want to bind a DOM element to my viewModel. 所以,我想将DOM元素绑定到我的viewModel。 The price attribute in the model is initialized with the value 99.00. 模型中的price属性初始化为值99.00。 When the price is changed (in Javascript) the DOM value of #price should also be updated. 当价格改变时(在Javascript中),#price的DOM值也应该更新。

I hope the question is clear to you guys. 我希望你们这个问题很清楚。

Thanks a lot for your time! 非常感谢你的时间!

Your view model should be initialized as follows: 您的视图模型应初始化如下:

var viewModel = { 
    price: ko.observable(jQuery("#price").text()) 
} 

<span id="price" data-bind="text: price">99.00</span> 

After that you should be using javascript to update the model, not the view. 之后你应该使用javascript来更新模型,而不是视图。 So instead of: 所以代替:

jQuery("#price").text('some new value');

.. you should be writing... ..你应该写...

viewModel.price('some new value');

This approach would be more in keeping with the MVVM pattern. 这种方法更符合MVVM模式。

Try using a dependant observable 尝试使用依赖的observable

var viewModel = {
    price: ko.observable(109)
}

viewModel.priceElement= ko.dependantObservable(function(){
    viewModel.price();
    return jQuery("#price");
})

This will update everytime you change the price. 每次更改价格时都会更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM