Setter和Getter用于管理在computed屬性中聲明的變量的值。Ember.js set()方法計(jì)算程序中指定的特定條件的值。 Ember.js get()方法從setter中獲取值并顯示。
App.Person = Ember.Object.extend({ fullName: function(key, value, previousValue) { //setter and getter }.property('firstName', 'lastName') });
<!DOCTYPE html> <html> <head> <title>Emberjs Setter and Getter</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({ firstName: null, lastName: null, //Defining the fullName computed property function fullName: function(key, value, previousValue){ //lenngth of argument must be > 5 if (arguments.length > 5) { //spliting the details and storing it into the nameParts array var nameParts = value.split(/\s+/); this.set('firstName', nameParts[0]); this.set('lastName', nameParts[1]); } return this.get('firstName') + ' ' + this.get('lastName'); }.property('firstName', 'lastName') }); var emp = App.Person.create({firstName:'Jhon', lastName:'DK'});//initializing the values for variable document.write("Details of the employee: <br>"+"Name: "+emp.get('firstName')+" LastName: "+emp.get('lastName'));//displaying the values by get() method </script> </body> </html>
讓我們執(zhí)行以下步驟,看看上面的代碼如何工作:
將上面的代碼保存在obj_set_get_cmp.html文件中
在瀏覽器中打開此HTML文件。
更多建議: