在我的Meteor应用程序中,我有以下处理程序,返回“贡献者”记录:

Template["IntroductionWizard_Step_1"].helpers({
  contributor: function(n) {
    return ContributorCollection.findOne({contributorName: ""});
  }
});
.

此记录正在反应模板中使用:

<input type="text" id="name" name="name" class="form-control-element" value="{{contributor.contributorName}}" 
.

正如我所理解的那样,这个模板要跟踪此记录更改的原因是因为它来自反应源。 我想知道的是创建实际贡献者对象是否有意义,并返回它而不是仅记录。但是,如果我这样做,那么这个对象就不会被观察到变化,或者会呢? 另一个词,可以将一种更传统的面向对象的方法与流星一起使用,具有这种模型对象,作为可观察到的和反应性(双向绑定)作为这些收集记录?

有帮助吗?

解决方案

您可以做任何您想要的 - JavaScript是一个基于原型的,所以它足以获得正确的原型并修改它。

要增强收集元素的行为,需要使用transform方法:

Contributor = function(doc) {
  _.extend(this, doc); // initialize object with contents of doc
  ...
};

Contributors = new Meteor.Collection('contributors', {
  transform: function(doc) {
    return new Contributor(doc);
  },
});
.

现在您可以将方法添加到贡献者的原型:

_.extend(Contributor.prototype, {
  someFunction: function() {...},
  otherFunction: function() {...},
  ...
});
.

如果要调整收集方法,它甚至更简单:

Contributors._findOne = Contributors.findOne;

Contributors.findOne = function() {
  var contributor = Contributors._findOne.apply(this, arguments);
  if(!contributor) {
    // initialize and save new contributor
    ...
  }
  return contributor;
};
.

使用这些技术,您可以将所需的行为注入收集及其元素。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top