如何在每种情况下访问数据上下文和模板实例(事件,帮助器,钩子)?

时间:2016-01-27 20:11:43

标签: meteor meteor-blaze meteor-helper

由于所有的不一致,我的大脑受到伤害。请查看下面的代码并更正/完成它:

{{1}}

1 个答案:

答案 0 :(得分:7)

这是答案,甚至可以显示更多。它包括创建和访问附加到模板的reactive-var或reactive-dictionaries。对Meteor开发人员来说,这一切都非常重要:

Template.Example.onCreated(function () {
  instance = this; // or = Template.instance();
  // instance_reactive_data_context = no point in having a reactive data context since this function is only executed once
  instance_nonreactive_data_context = this.data;
  // now in order to attach a reactive variable to the template:
  let varInitialValue = ...
  instance.reactive_variable = new ReactiveVar(varInitialValue);
  // and now let's attach two reactive dictionaries to the template: 
  let dictInitialValue_1 = { ... }
  let dictInitialValue_2 = [ ... ]
  instance.reactive_dictionaries = new ReactiveDict();
  instance.reactive_dictionaries.set('attachedDict_1', dictInitialValue_1);
  instance.reactive_dictionaries.set('attachedDict_2', dictInitialValue_2);
});

Template.Example.events({
  'click #example': function(event, template) {
    instance = template; // or = Template.instance();
    instance_reactive_data_context = Template.currentData();
    instance_nonreactive_data_context = template.data;
    event_data_context = event.currentTarget;
    // to access or modify the reactive-var attached to the template:
    console.log(template.reactive_variable.get());
    template.reactive_variable.set('new value');
    // to access or modify one of the reactive-dictionaries attached to the template:
    console.log(template.reactive_dictionaries.get('attachedDict_2'));
    template.reactive_dictionaries.set('attachedDict_2', { newkey: 'new value', somearray: ['a', 'b'] });
});

Template.Example.helpers({
  example: function() {
    instance = Template.instance();
    instance_reactive_data_context = this; // or = Template.currentData();
    // instance_nonreactive_data_context = it can't be accessed as a non-reactive source. When you'll need something like this, most likely because the helper is running too many times, look into the [meteor-computed-field][1] package
    // to access or modify the reactive-var attached to the template:
    console.log(Template.instance().reactive_variable.get());
    Template.instance().reactive_variable.set('new value');
    // to access or modify one of the reactive-dictionaries attached to the template:
    console.log(Template.instance().reactive_dictionaries.get('attachedDict_2'));
    Template.instance().reactive_dictionaries.set('attachedDict_2', 'new value here');
    // obviously since you declared instance on the first line, you'd actually use everywhere "instance." instead of "Template.instance()."
  }
});