流星 + 铁路由器 - 如何更新模板的数据上下文以响应用户在我的模板中生成的事件?



所以我有一条设置模板的路线

Router.route('audit', {
    path: '/audit/:audit_id/',
    template: 'audit',
    data: function() {
        if (this.ready()) {
            audit_obj = Audits.findOne({_id: this.params.audit_id});
            lineitems = LineItems.find(JSON.parse(audit.query));
            return {
                audit_obj: audit_obj,
                lineitems: lineitems
            }
        }
    },
    waitOn: function () {
        return [
            Meteor.subscribe('lineitems', this.params.audit_id),
            Meteor.subscribe('audits')
        ]
    }
}

现在,当我的用户对审核模板呈现的页面执行某些操作时,我想更新审核对象,并更新运行页面的数据上下文。 这可能吗?

像这样:

Template.audit.events({
    'click .something-button': function() {
        // update the data context for the current audit template.
        current_context.audit_obj.something = 'new something';
    }
});

是:

Router.route('audit', {
    path: '/audit/:audit_id/',
    template: 'audit',
    onRun: function() {
        Session.set('audit', Audits.findOne(this.params.audit_id));
        Session.set('lineitems', LineItems.find(JSON.parse(audit.query)).fetch());
    }
    data: function() {
        if (this.ready()) {
            return {
                audit_obj: Session.get('audit'),
                lineitems: Session.get('lineitems')
            }
        }
    },
    waitOn: function () {
        return [
            Meteor.subscribe('lineitems', this.params.audit_id),
            Meteor.subscribe('audits')
        ]
    }
}

Template.audit.events({
    'click .something-button': function() {
        // update the data context for the current audit template.
        Session.set('audit', {..});
    }
});

但是,您需要决定如何处理来自服务器的更改,这些更改可能会干扰前端的更改。因此,更好的方法可能是将代码的第一部分(路由器)保留原样:

Router.route('audit', {
    path: '/audit/:audit_id/',
    template: 'audit',
    data: function() {
        if (this.ready()) {
            return {
               audit_obj: Audits.findOne(this.params.audit_id),
               lineitems: LineItems.find(JSON.parse(audit.query))
            }
        }
    },
    waitOn: function () {
        return [
            Meteor.subscribe('lineitems', this.params.audit_id),
            Meteor.subscribe('audits')
        ]
    }
}

只需更改前端即可更新集合:

Template.audit.events({
    'click .something-button': function() {
        // update the data context for the current audit template.
        Audits.update( this.data.audit_obj._id, {..} );
    }
});

当然,这也将更新服务器上的数据。

最新更新