【问题标题】:MeteorJS Blaze.getData() occasionally returns undefinedMeteorJS Blaze.getData() 偶尔会返回 undefined
【发布时间】:2015-06-15 10:21:50
【问题描述】:

我目前正在使用 MeteorJS 的“renderWithData”方法在我的网页上渲染引导模式,以便在需要时加载每个模板。

我遇到了一个问题,我的帮助方法使用“Blaze.getData()”访问模式中的数据偶尔会返回未定义,我不确定如何解决这个问题。

我能够复制该问题的唯一方法是不断创建/销毁模态,并且似乎没有任何具体原因导致该问题。

以下是我一直在采取的步骤:

1) 我用正确的数据实例化模态

Template.Courses.events({
'click .share-course': function (e,t) {
    var courseID = $(e.target).data('courseid');

    Template.instance().activeCourse.set(
        createModalWithData(
            {
                currentInstance: Template.instance().activeCourse.get(),
                template: Template.Enrollment_Generator,
                dataToRender: {courseID: courseID}
            }
        ));

    $('#generateEnrollmentURL').modal('show');
}
});

另外,这里是“createModalWithData”的代码:

// Create a modal with a specific data context
// If modal template already exists, destroy
// and re-create with the new data context.
// If a location to render isn't specified, renders
// content in the body .
// Parameters: [Object] data { currentInstance : Template || null,
//                             template        : Template,
//                             dataToRender    : Object,
//                  (optional) location        : Element
// Return: Blaze Template Instance
createModalWithData = function createModalWithData(data) {

    // Ensure data exists
    if (_.isUndefined(data) || _.isNull(data)) {
        throw "data cannot be null or undefined";
    }

    // If modal already exists, destroy it
    if (!_.isNull(data.currentInstance)) {
        Blaze.remove(data.currentInstance);
    }

    // If location is undefined, set to page body
    if (_.isUndefined(data.location)) {
        data.location = document.body;
    }

    // Render modal with dataToRender
    return Blaze.renderWithData(data.template,
        data.dataToRender,
        data.location
    );
};

2) 我尝试在模态模板中使用“Blaze.getData()”检索数据

Template.Enrollment_Generator.onCreated(function() {
    var courseID = Blaze.getData().courseID; // Occasionally undefined

    Meteor.subscribe('enrollment-codes',courseID);
});

到目前为止,我已经尝试用“onRendered”替换“onCreated”方法,但仍然遇到同样的问题。

【问题讨论】:

    标签: meteor meteor-blaze


    【解决方案1】:

    原来问题出在点击事件中。我的分享课程按钮中有一个嵌套的 span 元素:

    <small class="share-course" data-courseid="{{_id}}">
         Share
         <span class="glyphicon glyphicon-share"></span>
    </small>
    

    这搞乱了我定位嵌入式课程 ID 的方式

    除了 Blaze.getData(),我还应该使用 Template.currentData() 来检索模板中的数据

    如此处所述:https://forums.meteor.com/t/blaze-getdata-question/5688

    【讨论】:

      猜你喜欢
      • 2020-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-27
      • 2014-01-04
      • 2011-06-11
      • 2015-02-26
      • 1970-01-01
      相关资源
      最近更新 更多