Ember.js Getting Started Guide-compute properties (compute property)

Source: Internet
Author: User
Tags ember js

This series of articles is all from (http://ibeginner.sinaapp.com/), please visit the original website.
1, simple calculation of properties

In a nutshell, a computed property is simply declaring a function as a property. This is actually the property defined for the class at the time of the class extension.

person = ember.object.extend ({    firstname:  null,    lastName: null,       //   fullName  is a computed attribute     fullname: ember.computed (' firstName ',  ' lastName ' ,  function ()  {        return this.get (' FirstName ')  +  ", "  + this.get (' LastName ');     })}); //   Instantiate simultaneous incoming parameter var piter = person.create ({    firstname:  ' Chen ',     lastName:  ' Ubuntuvim '}); Console.log (Piter.get (' FullName '));  // output  >>   chen, ubuntuvim 

The computed property is actually a function, and if you have touched on jquery, ExtJS believe you are very familiar with it, in both frameworks the function is so defined. Only in Ember, this function is treated as a property, and the return value of the function can be obtained through get.


2, calculating the attribute chain

In a ember program, a computed property can also invoke another computed property, form a computed attribute chain, or extend a method. Add a description () method based on the previous instance.

Person = ember.object.extend ({    firstname: null,     lastname: null,    age: null,    county: null,        //  fullName  is a computed attribute     fullname:  ember.computed (' firstName ',  ' LastName ',  function ()  {         return this.get (' firstName ')  +  ", "  + this.get (' LastName ');     }),     description: ember.computed (' FullName ',  ' age ',  ' County ',  function ()  {        return this.get (' FullName ' )  +  " age "  + this.get (' age ')  +  " county "  +  This.get (' County ');     }); //   instantiation Pass in parameters at the same time var piter =  Person.create ({   &NBsp;firstname:  ' Chen ',    lastname:  ' Ubuntuvim ',     age:  25,    county:  ' China '); Console.log (piter.get (' description '));   //  output >>   chen, ubuntuvim

When the user uses the Set method to change the value of the FirstName, and then calls get (' description ') The resulting value is also the updated value.


3, override the Get, set method of the computed property

Note that to pass the re-attribute as a parameter to the computed method, to distinguish the method of defining the computed attribute, the last parameter of the computed method is a function when it is defined, and the last argument when overridden is a hash.

     override the Get, set method Person = ember.object.extend of the computed property ({     firstname: null,    lastname: null,       //    override computed Properties FullName get, set method     fullname: ember.computed (' FirstName ',  ' LastName ',  {        get (key)  {             return this.get (' firstName ')  +  ","  +  This.get (' LastName ');        },         set (Key, value)  {             //   This official document uses the code, but when I run it appears  uncaught syntaxerror: unexpected token [    This error, do not know whether it is missing a file, follow up will fill up;//             Console.log ("value = " + value);//            var [  Firstname, lastname ] = value.split (/\s+/);              var firstname = value.split (/\s+/) [0];             var lastname = value.split (/\s+/) [1];             this.set (' FirstName ',  firstName);             this.set (' LastName ',  lastName);                     }    }),//     cannot override the get, set method for normal properties//     firstname: ember.computed (' FirstName ',  {//        get (key)  {//             return this.get (' FirstName ')  +  "@@";//         },//        set (key,  Value)  {//            this.set (' FirstName ',  value) (//        }//    })});    var jack = person.create ();    jack.set (' FullName ',  "James kobe") ; Console.log (Jack.get (' firstName ')); Console.log (Jack.get (' lastName '));

4, calculate the statistic of the attribute value

We often encounter this situation: a computed property value is dependent on an array or other object, such as in the case of Ember JS todos this section of code.

Export Default Ember.Controller.extend ({todos: [Ember.Object.create ({isdone:true}), Ember.Object.create ({ISDO    Ne:false}), Ember.Object.create ({isdone:true})], remaining:Ember.computed (' [email protected] ', function () {    var todos = this.get (' Todos ');  Return Todos.filterby (' IsDone ', false). Get (' length '); })});

Calculated PropertiesRemainingis the value of the dependent arrayTodos. Here's another point of knowledge: in the code aboveComputed ()there is one in the method[email protected]such a key, which contains a special key"@each"(you'll see more special keys later. )“[]”). It is important to note that this key cannot be nested and can only get one level of properties. Like[email protected](get the multi-layered attribute, here is the firstFooGet It againNameor[email protected]@each. Name (Nesting)Both of These methods are not allowed. “[email protected]”.

Ember automatically updates the calculated property values for the binding in the following 4 scenarios :

    1. < Span style= "font-family: Arial" > in todos Any of the objects in the array isdone toward Todos

    2. < Span style= "font-family: Arial" > from todos

    3. todos

< Span style= "font-family: Arial" > For example, the following code demonstrates the result;

Task = ember.object.extend ({  isdone: false  //   default = false});  workerlists = ember.object.extend ({  //   defines a Task object array   lists:  [    task.create ({ isdone: false }),     Task.create ({ isdone: true }),     task.create (),     Task.create ({ isdone: true }),     task.create ({ isdone: true  }),     task.create ({ isdone: true }),     Task.create ({ isdone: false }),     task.create ({ isDone: true  })   ],   remaining: ember.computed (' [email protected] ',  function ()  {    var lists = this.get (' lists ');    //    Query Property Isdone an object with a value of false and returns its number &NBSP;&NBSP;&NBsp; return lists.filterby (' IsDone ',  false). Get (' length ');   })}); //  The following code uses the API see:http://emberjs.com/api/classes/ember.mutablearray.htmlvar wl =  Workerlists.create ();//   all Isdone property values have not been modified Console.log (' 1,>> not complete lenght  is  '  + wl.get (' remaining ');   //  output 3var lists =  wl.get (' lists ');  //   gets the array inside the object  // -----   demonstrates the first case: 1.  When the Isdone property value of any object in the Todos array changes,;//   modifies the Isdone   value of an element of an array var item1 =  Lists.objectat (3);  //   get the 4th element  objectat () method is Ember provide us with// console.log (' item1  =  '  + item1); Item1.set (' IsDone ',  false); Console.log (' 2,>> not  complete lenght is  '  + wl.get (' remaining '));   //  output 4  //  --------- 2.   add to Todos arrayThe time of the element; Lists.pushobject (Task.create ({ isdone: false }));   // Added an object with a isdone of false console.log (' 3,>> not complete lenght is  '  +  Wl.get (' remaining '));  //  output 5 //  --------- 3.   Deleting an element from the Todos array; lists.removeobject (item1);  //  Deletes an element Console.log (' 4,>> not  complete lenght is  '  + wl.get (' remaining '));   //  output 4  //  --------- 4.   when the Todos array in the controller is changed to another array;//   Create a Controllertodoscontroller = ember.controller.extend ({  //  defines an array of additional task objects within the controller   todosincontroller: [    task.create ({ isdone: false }),     task.create ({ isdone: true })   ],  //   Use the key "@each. IsDone" to traverse the resulting Filterby () method to filter the IsDone property of the object   remaining: fThe Unction ()  {    //  remaining () method returns an array within the controller     return  this.get (' Todosincontroller '). Filterby (' IsDone ',  false). Get (' length ');   }.property (' @ Each.isdone ')   //   specify traversed properties}); Todoscontroller = todoscontroller.create (); var  count = todoscontroller.get (' remaining '); Console.log (' 5,>> not complete  lenght is  '  + count);   //  output 1

In the above case, we are the focus of the object is on the object's properties, but in practice often we do not relate to the properties of the object is changed, but the array elements as a whole object processing, compared to the above code we only care about the changes in the array object elements, Instead of changing the Isdone property of the object. In this case you can look at the following example, using the key "[]" instead of the key "@each. Foo" in the example. The changes from the keys can also be seen in their differences.

Task = ember.object.extend ({  isdone: false,  //   defaults to false   name:  ' TaskName ',  //   to display the results conveniently, rewrite the toString () method   toString:  function ()  {    return  ' [name =  ' +this.get (' name ') + ',  isdone  =  ' +this.get (' isDone ') + '] ';   }});  workerlists = ember.object.extend ({   //   defines a Task object array   lists: [    task.create ({  isdone: false, name:  ' ibeginner.sinaapp.com '  }),     task.create ({  isDone: true, name:  ' i2cao.xyz '  }),     task.create (),     task.create ({ isdone: true, name:  ' Ubuntuvim '  }),     task.create ({ isdone: true , name:  ' [email protected] '}),     task.create ({ isdone: true })   ],   index: null,  indexOfSelectedTodo:  ember.computed (' index ',  ' lists.[] ',  function ()  {    return this.get (' Lists '). Objectat (This.get (' index '));   })});   var wl = workerlists.create () ;//   all Isdone attribute values have not been modified Var index = 1;wl.set (' index ',  index); Console.log (' Get   ' +wl.get (' Indexofselectedtodo '). ToString () + '  by index  '  + index);

Ember.computed This component has many methods that use key "[]" implementations. This is especially true when you want to create a computed property that is an array. You can use Ember.computed.map to build your computing properties.

Const hamster = ember.object.extend ({  chores: null,  excitingchores:  ember.computed (' chores.[] ',  function ()  { //tells Ember chores is an array      return this.get (' chores '). Map (function (chore, index)  {       //return  ' ${index} --> ${chore.touppercase ()} ';  //   can use an ${} expression, And in the expression can directly invoke the JS method       return  ' ${chore} ';   //returns the element value    &NBSP;&NBSP,}),   }); //   an array assignment const hamster = hamster.create ({   //   name chores to define the name of the specified array with the class hamster   chores: [' first value ',  ' write  more unit tests ']});  console.log (Hamster.get (' excitingchores ')); Hamster.get (' chores '). Pushobject ("Add item test");  //add an item to chores  Arrayconsole.log (Hamster.get (' ExcitingchoreS ')); 

     ember also provides another way to define the computed properties of an array type.

Const Hamster = Ember.Object.extend ({chores:null, excitingChores:Ember.computed (' chores.[] ', function () {return T  His.get (' chores '). Map (function (chore, index) {//return ' ${index}--${chore.touppercase ()} ';  The ${} expression can be used, and the JS method return ' ${chore} ' can be called directly within the expression;  return element value}); })}); The array assignment const Hamster = hamster.create ({///name chores to be identical to the name of the class hamster definition specified array chores: [' first Value ', ' Write more unit tes ts ']});  Console.log (Hamster.get (' excitingchores ')); Hamster.get (' chores '). Pushobject ("ADD Item Test"); Add an item to chores Arrayconsole.log (Hamster.get (' excitingchores '));


Ember.js Getting Started Guide-compute properties (compute property)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.