Template.myTemplate.rendered直到页面刷新后才呈现

时间:2014-08-29 15:26:48

标签: javascript meteor

避免错误"模板助手中的异常:TypeError:无法读取属性' profile'未定义"我检查Meteor.user()是否返回了一个对象:

Template.create.isActive = function () {
  var user = Meteor.user();
  return user && user.profle.isActive;
};

当我实现此更改时,它会解决错误消息,但会产生新问题......' Template.create.rendered = function()'不再呈现。它仅在刷新页面后呈现。知道如何解决这个问题吗?

更新

Template.myTemplate.rendered中的代码......

Template.create.rendered = function() {
  if (!this._rendered) {
    this._rendered = true;

    // Form validation
    $("#create").bootstrapValidator({
      feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
      },
      /* submitButtons: '#fakeSubmit', Trick validator until https://github.com/nghuuphuoc/bootstrapvalidator/pull/244 is fixed */
      submitHandler: function(validator, form, submitButton) {
        var $form = $('#buildingCreate');

        var building = {
          company: $form.find('[name=company]').val(),
          address: $form.find('[name=address]').val(),
          floor: $form.find('[name=floor]').val()
        };

        Meteor.call('ensureBuilding', building.company, building.address, building.floor);

        Router.go('create');
      },
      fields: {
        company: {
          trigger: 'blur',
          validators: {
            notEmpty: {
              message: 'Please provide the company name'
            }
          }
        },
        address: {
          trigger: 'blur',
          validators: {
            notEmpty: {
              message: 'Please provide the company address'
                }
              }
            },
            floor: {
              trigger: 'blur',
              validators: {
                notEmpty: {
                  message: 'Please provide the floor'
                }
              }
            }
          }
        })
      }
    };

1 个答案:

答案 0 :(得分:0)

来自rendered文档:

  

当Template.myTemplate的实例呈现到DOM节点并首次放入文档时,将调用此回调。

如果#create位于{{#if}}块内,且模板呈现时为false,则验证将不会初始化。

更改

<template name="parent">
  {{> create}}
</template>

<template name="create">
  {{#if isActive}}
    <div id="create"> ... </div>
  {{/if}}
</template>

<template name="parent">
  {{#if isActive}}
    {{> create}}
  {{/if}}
</template>

<template name="create">
  <div id="create"> ... </div>
</template>

这样,#create在调用rendered时肯定会在DOM中。此外,鉴于渲染仅被调用一次,您不应该需要if (!this._rendered) ...