简体   繁体   English

如何从流星视图的更改事件更新模型?

[英]How can I update model from change event of meteor view?

I have a meteor application. 我有一个流星应用程序。 It has a simple data model, and edit screen. 它具有简单的数据模型和编辑屏幕。 The model is following: 该模型如下:

{
   _id: "some_id",
   date: "date",
   attempts: [{k1: "v1"}, {k1: "v2"}, {k1: "v1"}]
}

This model is stored in session. 该模型存储在会话中。 Edit screen is organasied in the following way: 编辑屏幕的组织方式如下:

<template name="editModel">
    <form>
        {{#each model.attempts}}
            {{> attempt}}
            <hr/>
        {{/each}}
    </form>
    <button class="btn add-rep">Add</button>
    <hr/>
    <button type="submit" class="btn btn-primary submit-exercise">Submit</button>
</template>

<template name="attempt">
    <label>K1</label>
    <select name="k1">
        <option {{selected k1 "1"}} >1</option>
        <option {{selected k1 "2"}} >2</option>
    </select>
</template>

The attempt template basically is just dropdown, that should update k1 property of object. attempt模板基本上只是下拉菜单,应该更新对象的k1属性。 I wrote following code: 我写了以下代码:

function keyChanged (e, t){
    t.data.k1 = t.find("[name='k1']").value;
}

Template.attempt.events = {
    "change select[name='grip']"    : keyChanged
}

But it does not work, because data is read only. 但这是行不通的,因为data是只读的。 The question is: how can I update that object inside attempts array? 问题是:如何在attempts数组中更新该对象?

You've not given enough detail on your collection to go on, but you would update your collection directly to change your model's data, or use what you're using as your model engine to do it. 您没有提供足够详细的数据集来进行下去,但是您将直接更新您的数据集以更改模型的数据,或者使用您用作模型引擎的数据来进行更新。

Eg to update your collection directly (add something to that array): 例如直接更新您的收藏集(向该数组添加内容):

Collection.update(id_of_record,{attempts : { $addToSet: {k1:"v9"} } });

So this would add a new record to the set. 因此,这会将新记录添加到集合中。 Have a look at all the operations possible , with the mongodb docs on arrays such as $addToSet the only thing you can't do for the moment is use the $ positional operator 看一下所有可能的操作 ,使用诸如$addToSet之类的数组上的mongodb文档,当前唯一不能做的就是使用$ positional运算符

As soon as you update your collection the corresponding template data would update using reactivity. 更新集合后,相应的模板数据将使用反应性进行更新。 I would be a bit careful and use {{#isolate}} & {{#constant}} with your use case to ensure the data around your HTML is rendered without having the entire template redraw so. 我会有点小心,并在您的用例中使用{{#isolate}}{{#constant}}来确保呈现HTML周围的数据而无需重新绘制整个模板。 See Reactivity Isolation & Constant Regions 请参阅反应性隔离恒定区

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

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