這裏是我的問題:流星JS:如何防止使用Meteor.call插入集合時的雙重渲染?
在一個模板事件處理程序,我使用Meteor.call()
調用一個方法來將文檔插入集合。
由於某些原因,這會導致關聯的模板呈現兩次而不是一次。如果我在事件處理程序中直接使用Collection.insert()
,則該模板只會呈現一次。我很困惑它爲什麼會渲染兩次。數據更改時,如何防止模板呈現兩次?
這裏是我的代碼:
Posts = new Meteor.Collection('posts');
if (Meteor.isClient) {
Template.postItem.rendered = function(e){
console.log("This was rendered");
}
Template.postsList.helpers({
posts: function() {
return Posts.find();
}
});
Template.postsList.events({
'submit form' : function (e) {
e.preventDefault();
var post = {
title: $(e.target).find('[name=title]').val(),
}
// This causes double render
Meteor.call('post', post, function(error, id){
if (error) {
console.log(error);
}
});
// This causes only a single render
//Posts.insert(post);
}
});
}
Meteor.methods({
post: function(attrs) {
return Posts.insert(attrs);
}
});
哦,孩子,這是令人沮喪的。我剛剛嘗試了提前生成ID作爲發送哈希的一部分的建議。這種工作,直到我做一些事情,如在服務器上添加一個時間戳文件,如'submit:new Date()。getTime()'。然後它會再次渲染兩次。 「隨機鹽」是什麼意思? – Chanpory
@Chanpory我的意思是: 1.我的方法有額外的參數'randomSeed'(它是可選的,btw) 2.然後,在它創建要插入的對象之後,它通過以下代碼行生成id: var id = Random.create([user._id,text,randomSeed]).id(); 3.然後它對集合執行「插入」操作。你可以嘗試'upsert' - 不知道 方法存根內有什麼區別。 – yeputons
這個問題有沒有更新? –