codecamp

EmberJS 对象模型声明观察器

不带原型扩展

使用不带原型扩展的Ember.observer方法定义内联观察器。

语句

App.ClassName = Ember.Object.extend({
   ComputedPropertyName: Ember.observer('ComputedPropertyNames', function() {
     //do the stuff
   })
});

类定义之外

使用addObserver将观察器添加到类定义之外的对象

语句

ClassName.addObserver('ComputedPropertyNames', function(){
  //do the stuff
});

例子

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs Declaring the Observer</title>
      <!-- CDN's -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script>
      <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js"></script>
      <script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"></script>
      <script src="https://builds.emberjs.com/release/ember.debug.js"></script>
      <script src="https://builds.emberjs.com/beta/ember-data.js"></script>
   </head>
   <body>
      <script type="text/javascript">
         App = Ember.Application.create();

         App.Person = Ember.Object.extend({
            //these values will be supplied by `create` method
            Name: null,

            fullName: function() {
               var Name = this.get('Name');
               return Name;
            }.property('Name'),

            fullNameChanged: Ember.observer('fullName', function(){
               //deals with the change
            })
         });

         var person = App.Person.create({ Name:'Manu',});
         person.set('Name','Jhon');
         document.write("Name Changed To: <br>");
         document.write('Name: '+person.get('fullName'));//displaying changed value
      </script>
   </body>
</html>

Output

让我们执行以下步骤,看看上面的代码如何工作:

  • 将上面的代码保存在obj_obsrvr_declr.html文件中

  • 在浏览器中打开此HTML文件。

温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }