gpt4 book ai didi

javascript - Meteor 更新集合不会在客户端刷新

转载 作者:行者123 更新时间:2023-12-02 16:15:35 27 4
gpt4 key购买 nike

我有一个具有样式属性的集合,我可以迭代这些样式属性并将其应用于相应的元素:

// server side
Meteor.publish('elements', function(){
return Elements.find();
});

//client side
Meteor.subscribe("elements");

setupElements = function () {
var currentUserId = Meteor.userId();
var elements = Elements.find({user: currentUserId}).fetch();
elements.forEach(function(e){
var elementId = e._id;
eval("document.getElementById('" + elementId + "').removeAttribute(\"style\")");
var width = e.width;
for (var i in width) {
eval("document.getElementById('" + elementId + "').style.width"= \"" + width[i] + "\"");
}
});
}

Template.element.rendered = function() {
if(!this._rendered) {
this._rendered = true;

// iterate through element and apply width style to each
setupElements();
}
}

// template
<template name="element">
{{#each element}}
<div id="{{_id}}" class="element">{{text}}</div>
{{/each}}
<button id="change-style">Change style</button>
</template>

模板渲染并将相应的宽度应用于每个元素。但是,当我触发如下更新时:

'click #change-style': function() {
Meteor.call('updateElements'); // assume server-method successfully updated all elements
setupElements(); // thought this will fetch new style and re-apply
},

文档在数据库中更新,但模板/ View 不会对更改使用react,直到我刷新页面或再次触发事件。当服务器更新数据库时,客户端似乎没有刷新数据库。想知道什么是使重新应用样式具有反应性的正确设置,或者是否有办法强制刷新模板。

提前致谢!

最佳答案

虽然使用标准响应式 html 和 JQuery 可能有更好的方法来完成您正在做的事情。在您的确切问题的上下文中:

Javascript 是异步的。 setupElements 在结果从服务器到达之前触发。只需在 .call 回调中触发它即可:

Meteor.call('updateElements', setupElements);

关于javascript - Meteor 更新集合不会在客户端刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29645930/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com