EmberJS 对象模型声明观察器
2018-01-03 17:47 更新
不带原型扩展
使用不带原型扩展的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文件。
以上内容是否对您有帮助:
更多建议: