簡體   English   中英

在Meteor.js中將變量范圍設置為模板

[英]Set a Variable Scope to Template in Meteor.js

是否可以創建一個范圍為模板的變量? 此變量可以在模板中的不同幫助程序之間共享,但不存在於模板外部。

在下面的這個例子中,如何在不重復定義的情況下在2個模板之間共享game變量? 使用var初始化它會使它全局化,這不是我想要的。 謝謝!

Template.userInfo.game = function() {
    var game = 'Angry Bird';
    return game + ' game';
};

Template.userInfo.score = function() {
    var game = 'Angry Bird';
    return game + ' score';
};

如果其他人偶然發現並使用Meteor 1.0,那么您可以通過以下方式實現這一目標。

Template.name.onCreated(function(){
    this.data.variableName = "something";
});

Template.name.helpers({
    'helper' : function() {
        return Template.instance().data.variableName;
    }
});

這樣,變量的范圍限定為創建的模板的實例。 我有一個頁面使用相同模板的多個實例,所以這非常有用。

編輯:

所以這適用於嵌套在另一個模板中的模板,但是對於父模板不能很好地工作。 data屬性沒有保留值,所以我做了一些更多的研究,並在Template.onCreated的例子中發現了這個 this.highlightedPicture = new ReactiveVar(null); 所以顯然可以在Template實例上定義新屬性。 我在兩種情況下都嘗試過這種方法,而且它適用於Template.instance()

為什么不用

Template.foo.created = function() {
    this._someVariable = "some value"
}

Template.foo.someHelper = function() {
    return this._someVariable
}

Template.foo.events({
    "click #mylink": function(event, tmpl) {
        console.log(tmpl._someVariable)
    }
})

在這種情況下,您的私有_someVariable不會為選項提供反應。 但是你可以包裝一個Deps.Dependency()來獲取私有的反應模板的變量

來自文檔: http//docs.meteor.com/#namespacing

只需用var聲明它,它就是文件范圍。 沒有var它將是全球范圍。

var game = 'Angry Bird'; // File scope.
game2 = 'Angry Bird'; // App scope.

我有一些問題要使用自動運行和變量范圍,所以它可能會幫助某人:

Template.foo.someHelper = function() {
     return this._someVariable
}

Template.foo.events({
     "click #mylink": function(event, tmpl) {
          console.log(tmpl._someVariable)
      }
})
Template.foo.onRendered(function() {
      this._someVariable = "some value"
      this.autorun(function(templateInstance) {
            Collection.find({}).fetch(); // Autorun will be executed each time this collection has change (update, delete, insert)
            console.log(templateInstance._someVariable);
      }, this.templateInstance());
});

您可以在onCreated中將其創建為反應式var,然后在幫助器中返回該變量。 無論您set何處set該變量,它都會自動更新輔助值。 這是一個例子:

Template.foo.onCreated(function() {
    this.yourVar = new ReactiveVar("");
    this.yourVar.set("initValue");
});

Template.foo.helpers({
    yourVar(){
        return Template.instance().yourVar.get();
    }
});

Template.foo.events({
    'click .btn': function (event) {
        template.yourVar.set($(event.target).val());
    }
});

現在,您可以在模板中的任意位置調用{{yourVar}} ,並按上述方式編輯其值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM