UI 更新 Meteor.js?

UI updates with Meteor.js?

我在找到添加到集合后更新 UI 的方法时遇到问题。因此,在下面的示例中,在您单击按钮并将其添加到集合后,将向 DOM 添加一个额外的输入。一切都很好,但我想找到一种方法来定位新的输入元素,并且最好在 CSS 之外给予它焦点。不幸的是,在 DOM 更新后,我找不到任何有助于解决此问题的信息。有任何想法吗?谢谢

<body>
  {{> myTemplate}}
</body>

<template name="myTemplate">
    {{#each myCollection}}
        <input type="text" value="{{name}}"><br>
    {{/each}}
    <br>
    <button>Click</button><input type="text" value="test" name="testBox">
</template>

test = new Meteor.Collection("test");

if (Meteor.isClient) {
    Template.myTemplate.rendered = function()
    {
        console.log("rendered");
        this.$('input').focus() 
    }
    Template.myTemplate.helpers({
        'myCollection' : function(){
            var testCollection = test.find({});
            console.log("helpers");
            return testCollection;
        }
    });
    Template.myTemplate.events({
        'click button': function(event){
            event.preventDefault();
            var val = $('[name="testBox"]').val();
            console.log("events");
            return test.insert({name: val});
        }
    });
}

在您的 myCollection 辅助函数中执行此操作。使用 jquery 定位模板中的最后一个输入并将其聚焦,添加 css。 Meteor 的模板助手是基于 DOM 对反应变量的使用的反应式计算,因此每次 DOM 根据您的集合更新时它都会 运行。

将您要添加的内容转换为模板并调用该模板的 rendered 以设置所需的 css 或执行任何需要的转换。

HTML:

<body>
  {{> myTemplate}}
</body>

<template name="item">
    <input type="text" value="{{name}}"><br>
</template>

<template name="myTemplate">
    {{#each myCollection}}
        {{> item this}}
    {{/each}}
    <br>
    <button>Click</button><input type="text" value="test" name="testBox">
</template>

JS:

test = new Meteor.Collection("test");

if (Meteor.isClient) {
    Template.myTemplate.onRendered(function() {
        console.log("rendered");
        this.$('input').focus() 
    });
    Template.myTemplate.helpers({
        'myCollection' : function(){
            var testCollection = test.find({});
            console.log("helpers");
            return testCollection;
        }
    });
    Template.myTemplate.events({
        'click button': function(event){
            event.preventDefault();
            var val = $('[name="testBox"]').val();
            console.log("events");
            test.insert({name: val});
        }
    });
    Template.item.onRendered(function() {
        this.$('input').focus();
    }
}

附带说明一下,您应该使用 onRendered 而不是 rendered,因为后者已被前者弃用。