【问题标题】:Meteor: IF statement returning true but page showing false (showing user Facebook picture)Meteor:IF 语句返回 true 但页面显示为 false(显示用户 Facebook 图片)
【发布时间】:2014-08-09 09:58:58
【问题描述】:

我试图在 facebook 用户登录时显示 facebook 图片,并在非 facebook 用户登录时显示占位符。

我在我的 user_page html 中创建了一个 if 语句:

        {{#if facebookuserloggedin}}
        TRUE
        <img src="http://graph.facebook.com/{{facebookuser}}/picture/picture?type=large" alt="{{user}}">
        {{else}}
        False
        <img src="user.png" alt="stanley">
        {{/if}}
        <h1>Welcome {{user}}</h1>

还有一个检查 facebook 登录状态的助手

 facebookuserloggedin: function(){
    FB.getLoginStatus(function (response) {
        console.log (response)
        if (response.status === 'connected') {
            (alert ("true"))
            return true
        }
        else {
            (alert("false"))
            return false
        }
    });

由于某种原因,警报显示帮助程序返回 true(当 facebook 用户登录时)但 html 页面显示为 false。因此,显示的是占位符而不是 facebook 个人资料图片。我真的不知道这是怎么发生的,有人可以帮我吗?提前致谢。

【问题讨论】:

  • 从您在此处显示的内容看来,您的助手将始终返回 undefined。内部回调是异步调用的吧?
  • 内部回调异步是什么意思?我是一个初学者,所以不完全理解这个概念。警报说真,页面说假。

标签: meteor


【解决方案1】:

正如@apendua 所说,辅助函数是同步的,而您调用的是异步函数。简而言之,这意味着您编写的return 语句不是您helper 函数的return 语句,而是您传递给FB.getLoginStatus 的函数。请注意,您使用了两次 function 关键字,因此您有两个函数,并且 return 语句在错误的那个中。

对于初学者来说这是一个常见的陷阱,所以不用担心,有一个简单的解决方法。它需要将你的状态存储在另一个地方(比如一个局部变量)并被动地观察它。

您可以在这里使用的模式很少。一开始,我建议在 rendered 回调中调用您的异步函数,并为结果创建一个单独的依赖项。这应该能让您对正在发生的事情有最好的了解。

var status = null
var statusDep = new Deps.dependency();

Template.templateName.rendered = function() {
    FB.getLoginStatus(function(response) {
        ...
        if(...) {
            status = true;
            statusDep.changed();
        } else {
            status = false;
            statusDep.changed();
        }
    });
};

Template.templateName.helpers({
    facebookuserloggedin: function() {
        statusDep.depend();
        return status;
    };
});

【讨论】:

  • 感谢您的帮助!这已经说明了很多。如果您有时间,能否快速解释一下 statusDep.depend() 的作用?
  • 简而言之:每当您在代码中的任何位置调用statusDep.changed() 时,都会导致函数重新计算。如需更详尽的说明,请阅读此处:http://docs.meteor.com/#deps_dependency
猜你喜欢
  • 2020-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多