![](/img/trans.png)
[英]Meteor JS: How do I insert a document into a collection, but only on the client-side?
[英]How do I run client-side code after a new collection item has been added to a Meteor view?
在我的模板中,我調用服務器端方法將項添加到集合中。 此集合顯示在頁面上。 渲染新項目后,我想將其重點放在用戶身上。
這是觸發服務器方法的助手。
'click .add-post-button': function(e) {
var userId = Template.parentData(0)._id;
Meteor.call('addPost', userId, function(error, result) {
Session.set('newPostId', result);
});
}
完成后,將顯示新項目。 我想專注於用戶。 以前,我嘗試使用jQuery在上面的回調中執行此操作,但這不起作用,因為它在回調運行時尚未添加到DOM。 現在,我正在嘗試使用渲染的回調:
Template.postsAdmin.rendered = function() {
var newPostId = Session.get('newPostId');
if (newPostId) {
var $newPostCell = $('#' + newPostId);
$newPostCell.find('.post').focus();
}
};
不幸的是,這似乎也沒有用。 將新項目添加到視圖時,此代碼不會運行。
在將新項目添加到視圖中以便聚焦新項目后,如何運行代碼?
您的原始代碼非常接近 - 您只需將焦點邏輯放入反應式上下文中,以便在會話變量更改時再次運行。 成功的最短途徑是使用模板自動運行 :
Template.postsAdmin.onRendered(function() {
this.autorun(function() {
var newPostId = Session.get('newPostId');
if (newPostId) {
var $newPostCell = $('#' + newPostId);
return $newPostCell.find('.post').focus();
}
});
});
但是,您可能遇到的一個問題是,您將遇到一個競爭條件,即在自動運行之后添加新帖子。 一個hacky解決方案是在上面添加一個超時。 一個改進的解決方案是將類似原始代碼的內容添加到新添加的post子模板的onRendered
回調中:
Template.post.onRendered(function() {
var newPostId = Session.get('newPostId');
if (newPostId === this.data._id) {
// add code here to focus this template instance
}
});
一種選擇可能是observeChanges
? 你能試試嗎?
在渲染函數中執行以下操作
Template.postsAdmin.rendered = function(){
var query = Posts.find({}); //your query
var handle = query.observeChanges({
added: function (id, user) {
//code to set focus???
}
});
}
只要有一個新項目添加到與您的查詢匹配的minimongo,就會運行此代碼。
加載數據后,請務必顯示模板。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.