使用不帶原型擴展的Ember.observer方法定義內(nèi)聯(lián)觀察器。
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>
讓我們執(zhí)行以下步驟,看看上面的代碼如何工作:
將上面的代碼保存在obj_obsrvr_declr.html文件中
在瀏覽器中打開此HTML文件。
更多建議: