Blaze模板遍历对象 [英] Blaze template iterate over object
问题描述
我正在尝试遍历blaze模板(流星)中的对象,在控制台中我可以看到数据,但模板上什么也看不到.如何使它正常工作? #each不起作用,arrayify也不起作用.
I am trying to iterate over an object in blaze template (meteor) , in console I can see the data but nothing on template.How can I get this working ? #each not working , arrayify also didn't work.
在评论中添加到这里:
{{#each contactList}}
<tr class="clickable" name="edit-contact" >
<td>{{name}} </td>
<td>{{email}} </td>
<td>{{title}}</td>
<td>{{phone1}}</td>
<td>{{phone2}}</td>
<td>{{phone3}}</td>
</tr>
{{/each}}
JS:
contactList: function() {
$.ajax({
url: Meteor.absoluteUrl()+'contacts/get_by_company/'+Session.get('company_id'),
type: 'GET',
error: function() { callback(); },
success: function(res) { console.log(res); return res; },
});
}
推荐答案
contactList
助手未向您提供期望的联系人列表的直接原因是您调用了异步函数( $.ajax
),并且在调用之后不返回任何内容.
The immediate reason for your contactList
helper not providing you with your expected list of contacts is that you call an asynchronous function ($.ajax
) and do not return anything after that call.
请参阅如何从异步调用?
流星不知道您的异步调用何时完成,也不知道其结果.
Meteor is not aware of when your asynchronous call completes, nor of its result.
如果您真的需要保持通话状态,可以将结果存储在 ReactiveVar
并在您的帮助器中阅读.流星知道只要有反应性源,它应该自动重新运行您的助手.在该助手功能中进行了更新.因此,模板到达后将自动接收结果.
If you really need to keep your AJAX call, you could store the result in a ReactiveVar
and read it in your helper. Meteor knows that it should automatically re-run your helper whenever a reactive source is updated within that helper function. Therefore, your template will automatically receive the result when it arrives.
import { ReactiveVar } from 'meteor/reactive-var'
var contacts = new ReactiveVar();
Template.templateName.onCreated(function () {
$.ajax({
url: Meteor.absoluteUrl()+'contacts/get_by_company/'+Session.get('company_id'),
type: 'GET',
error: function() { callback(); },
success: function (res) {
console.log(res);
contacts.set(res); // Update the reactive var.
return res; // Useless.
}
});
});
Template.templateName.helpers({
contactList: function () {
return contacts.get(); // Will get updated later on and Meteor will automatically refresh the helper.
}
});
话虽如此,@ jordanwillis指出,在Meteor中几乎不需要REST端点.如果您可以重构检索联系人列表的方式,则可以得到一种类似流星的结构,并具有所有优点(实时更新,操作客户端数据的灵活性等)
That being said, within Meteor there is hardly a need for REST endpoints, as pointed out by @jordanwillis. If you can re-factor the way you retrieve your contacts list, you can get a much more Meteor-like structure, with all its advantages (real time update, flexibility of manipulating the data client-side, etc.)
这篇关于Blaze模板遍历对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!