我在我的应用程序中定义了以下集合:
Projects = new Mongo.Collection("projects")在这个集合中,我插入了:
Projects.insert({
source: "https://upload.wikimedia.org/wikipedia/commons/7/7f/Pug_portrait.jpg",
title: "pug",
artist: "pug",
description: "This piece shows the duality of pug",
price: "priceless"
});
Projects.insert({
source: "http://i.stack.imgur.com/D2ABD.gif",
title: "doge",
artist: "doge",
description: "much doge, many deal with it, wow",
price: "bout tree fiddy"
})我试图使用以下助手函数创建图像源数组:
sourceArray : function () {
// returns array of sources
var sources = [];
for (var i = 0; i < Projects.find().count(); i++) {
sources.push(images[i].source);
}
return sources;
}“图像”变量以前定义为:images = Projects.find().fetch();
然后在HTML中调用helper函数。
<p>{{sourceArray}}</p>在页面上,第一个源会迅速出现,但在几秒钟内消失。在浏览器控制台中显示了以下内容:
meteor.js:888 Exception in template helper: TypeError: Cannot read property 'source' of undefined
at Object.Template.body.helpers.sourceArray (http://localhost:3000/art.js?913b8578eb54cde21abc07c994f6b29267232bc5:61:28)
at http://localhost:3000/packages/blaze.js?a5c324925e5f6e800a4c618d71caf2848b53bf51:2880:16
at http://localhost:3000/packages/blaze.js?a5c324925e5f6e800a4c618d71caf2848b53bf51:1651:16
at http://localhost:3000/packages/blaze.js?a5c324925e5f6e800a4c618d71caf2848b53bf51:2928:66
at Function.Template._withTemplateInstanceFunc (http://localhost:3000/packages/blaze.js?a5c324925e5f6e800a4c618d71caf2848b53bf51:3476:12)
at http://localhost:3000/packages/blaze.js?a5c324925e5f6e800a4c618d71caf2848b53bf51:2927:27
at Spacebars.call (http://localhost:3000/packages/spacebars.js?7bafbe05ec09b6bbb6a3b276537e4995ab298a2f:172:18)
at Spacebars.mustacheImpl (http://localhost:3000/packages/spacebars.js?7bafbe05ec09b6bbb6a3b276537e4995ab298a2f:109:25)
at Object.Spacebars.mustache (http://localhost:3000/packages/spacebars.js?7bafbe05ec09b6bbb6a3b276537e4995ab298a2f:113:39)
at null._render (http://localhost:3000/template.art.js?30aa5e2d0b6d3de2f69b7341296ae51b8ce737ba:27:22)异常指的是这一行代码:
sources.push(images[i].source);怎么解决这个问题呢?
发布于 2015-07-21 19:43:53
尝试:
sourceArray : function () {
var images = Projects.find().fetch();
var sources = [];
for (var i = 0; i < images.length; i++) {
sources.push(images[i].source);
}
return sources;
}如果如您所说,将图像定义为模板助手属性,则可能需要
this.images[i].source发布于 2015-07-21 19:44:22
只需在你的助手中重新定义它。这可能是你想要的,所以它将是被动的。下面是一个应该有效的实现:
sourceArray: function() {
return _.pluck(Projects.find().fetch(), 'source');
}https://stackoverflow.com/questions/31548126
复制相似问题