Rendr如何在RendrJS同构框架中将模型传递给子视图

Rendr how to pass model to subview in RendrJS isomorphic framework

本文关键字:模型 视图 RendrJS 框架 同构 Rendr      更新时间:2023-09-26

假设我正在构建一个博客,其中主页呈现博客文章列表。我的问题是如何将模型传递给每个孩子的后视图?

我有一个index.hbs在一个集合中迭代

{{#forEach models}}
    {{view "post_view" model=value model_name="story"}}
{{/forEach}}

我有一个post_view.js

var BaseView = require('./base');
module.exports = BaseView.extend({
     className: 'post_view',
    initialize: function() {
        console.log(this.model); //undefined
        console.log(this.options.model); //undefined on client, logs model attributes on server
    }
});
module.exports.id = 'post_view';

但模型似乎没有在post_view.js中设置。如果我在{{forEach}}循环中执行{{json value}},我可以看到打印的JSONified输出。我需要做什么来传递模型,我需要在视图中手动构建它吗?谢谢

我没有资格发表评论,但这不是一个答案。

当初始化子视图时,通常model还不存在。它肯定会在postRender()之前到达,并且应该在getTemplateData()之前到达。我不记得{{view}}插件的确切问题导致了这种竞争状况,但我以前肯定见过这种情况。虫洞就在这附近:https://github.com/rendrjs/rendr/blob/master/shared/base/view.js#L438并且是在服务器上工作但并不总是在客户端上工作的东西。

这就是我们一直在做的事情,它很好地将它进一步抽象,以便我们可以重用"列表"组件。

主页控制器

index: function(params, callback) {
    var spec = {
        posts: {
            collection: 'Posts',
            params: params
        }
    };
    this.app.fetch(spec, function(err, result) {
        callback(err, result);
    });
}

页面级模板(如主页)

<section class="container">
    <h2>Recent Posts</h2>
    {{view "posts/list" collection=posts}}
</section>

帖子列表模板(Posts/List.hbs)

<div class="media-list">
    {{#each _collection.models}}
        {{view "posts/item" model=this}}
    {{/each}}
</div>

或者,如果用于每个

{{#forEach _collection.models}}
    {{view "posts/item" model=value}}
{{/forEach}}

张贴项目模板(posts/Item.hbs)

<div class="media">
  <div class="media-body">
    <h4 class="media-heading">{{title}}</h4>
    {{description}}
  </div>
</div>

我也有这个链接,我用它来尝试把对我们有用的约定放在一起:

https://github.com/crwang/rendr-conventions

答案是parse()方法使用不当。我最初的故事集有一个像这样的属性

parse: function(rsp) {
    return rsp.stories;
}

因为API响应包含一些元数据以及"stories"键下的一系列stories。我删除了解析方法,而是添加了

 jsonKey: 'stories'

这解决了我的问题。