javascript Knockout JS 更新 DOM 后如何运行代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14399443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run code after Knockout JS has updated the DOM
提问by Magpie
As part of my view I have:
作为我观点的一部分,我有:
<ul data-bind="foreach: caseStudies">
<li><a data-bind="text: title, attr: { href: caseStudyUrl }"></a></li>
</ul>
I want to run some 3rd Party code once knockout has updated the DOM.
一旦淘汰赛更新了 DOM,我想运行一些第 3 方代码。
caseStudies(data);
thirdPartyFuncToDoStuffToCaseStudyLinks(); <-- DOM not updated at this point.
Any idea on how I can hook into knockout to call this at the correct time?
关于如何在正确的时间进行淘汰赛的任何想法?
回答by KodeKreachor
Using the afterRender
binding can help you.
使用afterRender
绑定可以帮助您。
<ul data-bind="foreach: { data:caseStudies, afterRender:checkToRunThirdPartyFunction }">
<li><a data-bind="text: title, attr: { href: caseStudyUrl }"></a></li>
</ul>
function checkToRunThirdPartyFunction(element, caseStudy) {
if(caseStudies.indexOf(caseStudy) == caseStudies().length - 1){
thirdPartyFuncToDoStuffToCaseStudyLinks();
}
}
回答by Rustam
One accurate way is to use the fact that KnockoutJS applies bindings sequentially (as they are presented in html). You need define a virtual element after 'foreach-bound' element and define 'text' binding that calls your third party function.
一种准确的方法是利用 KnockoutJS 顺序应用绑定的事实(因为它们在 html 中呈现)。您需要在“foreach-bound”元素之后定义一个虚拟元素,并定义调用第三方函数的“text”绑定。
Here is html:
这是html:
<ul data-bind="foreach: items">
<li data-bind="text: text"></li>
</ul>
<!-- ko text: ThirdParyFunction () -->
<!-- /ko -->
Here is code:
这是代码:
$(function () {
var data = [{ id: 1, text: 'one' }, { id: 2, text: 'two' }, { id: 3, text: 'three' } ];
function ViewModel(data) {
var self = this;
this.items = ko.observableArray(data);
}
vm = new ViewModel(data);
ko.applyBindings(vm);
});
function ThirdParyFunction() {
console.log('third party function gets called');
console.log($('li').length);
}