如何将数组传递给jade partial'之后'表示数组已完成加载

时间:2012-06-24 21:47:23

标签: node.js express pug

我有一个很好的紧密数组,如果我只能在组装完成后将其传递给部分,那么它将很好地呈现为玉部分。 (我已通过预加载确认了它)

我现在遇到的问题并且无法在任何地方找到答案,当我运行我的应用程序时,我无法使用或显示数组,直到它完成组装/加载自身..(其中填充了数据) - 所以我使用异步来运行构建数组的函数。效果很好。 - 一旦我确认它确实已构建完整的东西,我就调用一个函数done() - 现在我只想将数组传递给我的部分,但似乎我不能这样做,除非使用Ajax + JSON :(其中我试图避免,因为部分已经内置了实体迭代。

- 有人知道在应用程序运行后(不使用套接字)填充部分的简单方法吗?

//in my main app, web.js
//assume I have all the dependencies loaded
//setup an empty array
var items = new Array();

// then run 'fetch' which populates array with scraped data, takes about 10 seconds 
app.get('/', function(req, res){
    fetch(p.u[0]);  //builds the array, returns items[] 
    res.render('index.jade', {
        title: 'my first node.js app',
        item: 'items' //what the partial needs, this throws an error if I don't 
    })
});

//have to use this to avoid initial error due to array being empty/undefined when app
//first starts 
var params = {
    "namespace": {
        "items": [
            "an unnecessary value"
        ]
    }
};

//and finally this is what's called once the array is finished assembling itself
function displayItems(){
    app.get('/', function(req, res){
      req.render('items.jade', {item : 'items'})
    })  
}



//index.jade
//setup my partial
//script is there to avoid initial error due to array being empty/undefined when app
//first starts
div.list
  script
    if(namespace.items) {
      if(namespace.items.length) {
        != partial('item', items)
      }
    }


//and my partial, _items.jade
//express docs confirm that jade would iterate over each item in the items array 
//with this jade markup
ul.list
  li.date #{item.date}
  li.descrip #{item.descrip}
  li.reas #{item.reas}
  li.cmpny #{item.cmpny}
  li.photo #{item.photo}

2 个答案:

答案 0 :(得分:0)

已经很晚了,我不完全确定我理解你的问题,但如果你愿意等待10秒钟,你可以这样做,只是缓存结果:

var items = null;

app.get('/', function(req, res){
    function done(){
       res.render('index.jade', {
          title: 'my first node.js app',
          item: items
       }):
    }
    if( items == null ){
       return fetch(p.u[0], function(err,fetchedItems){
          if( err ) throw err;
          items = fetchedItems;
          return done();
       });
    }
    return done();
});
希望这会有所帮助。

或者可能不是:您在服务器端使用jade来组装页面,然后才能通过网络发送页面。

如果我理解正确,您希望向用户显示一个页面,并在10秒后在同一页面上显示结果(项目)而不重​​新加载。不使用套接字或Ajax,我无法完成此任务。

您可以等到数据准备就绪,或者显示一个页面,说当前正在加载数据,然后将其切换出来。

partials是页面片段或html片段,可以包含在.jade中,如!=partial(template name[, options])或者像express这样调用:res.partial(template name[, options]);。所有这些都发生在服务器上。

答案 1 :(得分:0)

如果你试图同步这样做,那么就要击败node.js和Express背后的整个想法。如果您的应用程序正在等待生成此数组的查询/脚本,而不是等待下一个http请求发生的情况?您应该重新构建应用程序以利用节点的ansync方法并将渲染作为回调传递:

app.get('/', function(req, res){
    var renderView = function(items) {
        return res.render('index.jade', {
            title: 'my first node.js app',
            item: items
        })
    };

    fetch(p.u[0], renderView);
});

你必须修改fetch()以接受第二个参数(回调),你必须使用items对象调用它。