nodeclub源码中EJS的疑惑
发布于 11 年前 作者 amaozhao 3898 次浏览 最后一次编辑是 8 年前

刚看到下nodeclub的源码里的模板 /views/topic/abstract.html 是这个样子


  <div class='user_avatar block'>
    <% if(topic.reply) {%>
      <a href="/user/<%= topic.reply.author.name %>">
        <img src="<%= topic.reply.author.avatar_url %>"
          title="<%= topic.reply.author.name %>"
        />
      </a>
    <% } %>
    ...
  </div>

看到 /user/<%= topic.reply.author.name %> 这里有点迷惑,topic的model里定义的是author_id,模板是怎么有author这个属性的?

望高手解答。

2 回复

我去怎么成这个样子了 重贴一下

<a href="/user/<%= topic.author.name %>">
  <img src="<%= topic.author.avatar_url %>"
    title="<%= topic.author.name %>"
  />
</a>

这段代码里的topic.author.name的author是哪里来的

这个????

首先你可以先了解下这个eventproxy模块,
这里有篇文章http://cnodejs.org/topic/4f76cafe8a04d82a3d556a07
或者你直接去https://github.com/JacksonTian/eventproxy这里看,

你看明白这个之后你在看这里:proxy/topic.js文件里的代码,随便一个函数都行,比如:

/**
 * 根据主题ID获取主题
 * Callback:
 * - err, 数据库错误
 * - topic, 主题
 * - tags, 标签列表
 * - author, 作者
 * - lastReply, 最后回复
 * @param {String} id 主题ID
 * @param {Function} callback 回调函数
 */
exports.getTopicById = function (id, callback) {
  var proxy = new EventProxy();           ----------重点注意0:这里有使用啊
  var events = ['topic', 'tags', 'author', 'last_reply'];
  proxy.assign(events, function (topic, tags, author, last_reply) {
    return callback(null, topic, tags, author, last_reply);
  }).fail(callback);

  Topic.findOne({_id: id}, proxy.done(function (topic) {
    if (!topic) {
      proxy.emit('topic', null);
      proxy.emit('tags', []);
      proxy.emit('author', null);         --------重点注意1:这里是空
      proxy.emit('last_reply', null);
      return;
    }
    proxy.emit('topic', topic);

    // TODO: 可以只查tag_id这个字段的吧?
    TopicTag.find({topic_id: topic._id}, proxy.done(function (topic_tags) {
      var tags_id = [];
      for (var i = 0; i < topic_tags.length; i++) {
        tags_id.push(topic_tags[i].tag_id);
      }
      Tag.getTagsByIds(tags_id, proxy.done('tags'));
    }));

    User.getUserById(topic.author_id, proxy.done('author'));       -------重点注意这里2:这里才是最重要的,如果你看懂刚才上面我推荐的,那么这里你应该就没有难度了!    
    
    if (topic.last_reply) {
      Reply.getReplyById(topic.last_reply, proxy.done(function (last_reply) {
        proxy.emit('last_reply', last_reply || null);
      }));
    } else {
      proxy.emit('last_reply', null);
    }
  }));
};

对了,github上面这句很重要啊,别漏掉了:

ep.done('tpl');
// 等价于
function (err, content) {
  if (err) {
    // 一旦发生异常,一律交给error事件的handler处理
    return ep.emit('error', err);
  }
  ep.emit('tpl', content);
}

你看明白了,你或许就知道为什么了!

回到顶部