简体   繁体   English

流星与“空”对象一起工作

[英]Meteor working with an “empty” object

What is the correct approach when working with an "new object" that is to be saved in a collection. 使用要保存在集合中的“新对象”时正确的方法是什么? Say I have a collection Cars. 说我有一个收集汽车。 I have a /cars/new-car url and then a form with: 我有一个/ cars / new-car网址,然后有一个表格:

name: __ 名称: __

parts: list of parts here 零件:零件清单在这里

If I want to make this form "reactive" in the sense that if I add a new part in the parts array it shows a rerender is the best approach to make the whole "Car" a reactive object. 如果要使这种形式具有“反应性”,即在部件数组中添加新零件,则表示重新渲染是使整个“汽车”成为反应性对象的最佳方法。 Or should one just add a new row in the dom? 还是应该在dom中添加新行?

I dont want to automatically insert the whole thing into the "Cars" collection until It has a name and a list of parts. 我不想自动将整个内容插入“汽车”集合中,直到它具有名称和零件列表为止。

Most examples shows very simple of adding to collection -> rerender of DOM which is very straightforward. 大多数示例显示添加到集合非常简单->重新呈现DOM,这非常简单。

Edit: The same concept may apply to when editing a car. 编辑:编辑汽车时,可能适用相同的概念。 Fetching the car from a collection, setting up so the returned object is reactive(so I can add/remove parts) when done get all values and store the edited car information. 从集合中获取汽车,进行设置,以使返回的对象具有反应性(这样我就可以添加/删除零件),完成后,获取所有值并存储编辑后的汽车信息。

Start out by initializing an "empty" car as a reactive variable. 首先将“空”汽车初始化为反应变量。

Template.cars.onCreated(function () {
  this.car = new ReactiveVar({}); // empty car
});

Say your dom has some sort of attribute on each field describing which key it is: 假设您的dom在每个字段上都有某种属性来描述它是哪个键:

<input data-key="name" placeholder="Car name"/>

Then you can bind an event that will use the data from this to update the reactive variable. 然后,您可以绑定一个事件,该事件将使用其中的数据来更新反应变量。

Template.cars.events({
  'change input': function (e, template) {
    template.car.set(_.extend(template.car.get(), {
      [$(e.target).data('key')]: $(e.target).val()
    }));
  }
});

This will construct the object as you fill in your inputs. 填写输入时,这将构造该对象。

Consider using Session for your /cars/new-car page 考虑在/ cars / new-car页面上使用Session

When the page first loads 页面首次加载时

Session.set('parts', []});
Session.set('name', '');

When the user saves a part 用户保存零件时

var addedPart = getPart();
var update = Session.get('parts').push(addedPart);
Session.set('parts', update);

Then your template helper functions can get everything it needs to render the view by calling Session.get(). 然后,您的模板帮助器函数可以通过调用Session.get()获得呈现视图所需的所有内容。

Template.view.helpers({
    currentParts: function() {
        return Session.get('parts');
    }
});

What do you think? 你怎么看? I'm fairly new to Meteor myself, so there maybe even more clever ways to do batch updates on the session. 我本人对Meteor还是很陌生,所以也许有更聪明的方法可以在会话中进行批量更新。 But this is general gist. 但这是一般要点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM