MeteorJS Blaze.getData() 偶尔 returns undefined

MeteorJS Blaze.getData() occasionally returns undefined

我目前正在使用 MeteorJS 的 "renderWithData" 方法在我的网页上呈现 bootstrap 模态,以便在需要时加载每个模板。

我 运行 遇到一个问题,我的辅助方法使用 "Blaze.getData()" 访问模态中的数据偶尔会 return 未定义,我不确定如何解决这个问题.

我能够重现该问题的唯一方法是不断 creating/destroying 模态,似乎没有任何具体原因导致该问题。

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

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" 方法,但仍然遇到同样的问题。

原来问题出在点击事件中。我的分享课程按钮中有一个嵌套的 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