Ember静态变量

时间:2014-01-10 21:54:30

标签: ember.js

我正在尝试让多个视图访问同一个变量。我想简单的解决方案是让控制器存储视图的变量。但无论如何在ember中声明静态变量?

3 个答案:

答案 0 :(得分:1)

解决方法是重新打开类并添加静态变量。 What is the ember.js idiomatic way to create static variables in model?

答案 1 :(得分:1)

有两种方法可以将变量定义为在Ember对象中表现为静态变量。一种方法是reopenClass函数,另一种方法是在Ember.Object的extend函数中定义类时定义变量。 下面的例子显示了这两种方式。

App.Person = Ember.Object.extend({
    data2: "Boban", // static variable
    setData: function(value){
           App.Person.data=value;
    },
    getData: function(){ return App.Person.data;},
    setData2: function(value){
        App.Person.prototype.data2=value;
    },
    getData2: function(){return  App.Person.prototype.data2;}
 }).reopenClass({
                 data: 123 // static variable
               });


 per1= App.Person.create();
 per2=App.Person.create();
 console.log("show 1 th...");
 console.log("data per1 : " + per1.getData());   //data per1 : 123
 console.log("data per2 : " + per2.getData());   //data per2 : 123
 console.log();
 per1.setData("data is set in per 1");
 console.log("show 2 th...");
 console.log("data per1 : " + per1.getData()); //data per1 : data is set in per 1
 console.log("data per2 : " + per2.getData());  //data per2 : data is set in per 1
 console.log();
 per2.setData("data is set in per2");
 console.log("show 3 th...");
 console.log("data per1 : " + per1.getData());  //data per1 : data is set in per2
 console.log("data per2 : " + per2.getData());   //data per2 : data is set in per2
 console.log();


console.log("show 11 th...");
console.log("data2 per1 : " + per1.getData2()); //Boban
console.log("data2 per2 : " + per2.getData2()); //Boban
console.log();
per1.setData2("data2 is set in per 1");
console.log("show 12 th...");
console.log("data2 per1 : " + per1.getData2()); //data2 per1 : data2 is set in per 1
console.log("data2 per2 : " + per2.getData2());  //data2 per2 : data2 is set in per 1
console.log();
per2.setData2("data2 is set in per2");
console.log("show 13 th...");
console.log("data2 per1 : " + per1.getData2()); //data2 per1 : data2 is set in per2
console.log("data2 per2 : " + per2.getData2());//data2 per1 : data2 is set in per2
console.log();

// end at last
per1.setData("D1");
per2.setData2("D2");

per1.set("data","df1");
per2.set("data","df2");

per1.set("data2","d2f1");
per2.set("data2","d2f2");

console.log("last ....")
console.log("per1 : " + per1.getData()  + "     " +  per1.get("data")  + "          " +  per1.getData2() + "     " + per1.get("data2"));
console.log("per2 : " + per2.getData()  + "     " +  per2.get("data")  + "         " +  per2.getData2() + "     " + per2.get("data2"));


 //per1 : D1     df1     D2     d2f1
 //per2 : D1     df2     D2     d2f2

可以看出,变量数据 data2 的行为类似于静态变量。如果您尝试使用功能集 .set('数据',' df')设置具有相同名称的变量,该变量是该实例的新变量,并且与定义相同的静态不一样。

答案 2 :(得分:0)

您还可以定义视图并在其中设置静态变量,其他视图可以扩展此视图。