can-define/list/list
Create observable lists.
new DefineList([items])
Creates an instance of a DefineList or an extended DefineList with enumerated properties from items
.
var DefineList = require("can-define/list/list");
var people = new DefineList([
{ first: "Justin", last: "Meyer" },
{ first: "Paula", last: "Strozak" }
])
Parameters
- items
{Array}
:An array of items to seed the list with.
Use
The can-define/list/list
module exports a DefineList
constructor function. It can be used
with new
to create observable lists that behave very similar to Array
s. For example:
var list = new DefineList(["a","b", "c"]);
list[0] //-> "a";
list.push("x");
list.pop() //-> "x"
It can also be extended to define custom observable list types with
extend. For example, the following defines a StringList
type
where every item is converted to a string by specifying the items definition (#)
:
var StringList = DefineList.extend({
"#": "string"
});
var strings = new StringList([1,new Date(1475370478173),false]);
strings[0] //-> "1"
strings[1] //-> "Sat Oct 01 2016 20:07:58 GMT-0500 (CDT)"
strings[2] //-> "false"
Non-numeric properties can also be defined on custom DefineList type. The following
defines a completed
property that returns the completed todos:
var TodoList = DefineList.extend({
"#": Todo,
get completed(){
return this.filter({complete: true})
}
});
var todos = new TodoList([{complete: true}, {complete:false}]);
todos.completed.length //-> 1
Finally, DefineList instances are observable, so you can use the can-event methods to listen to its add, length, remove, and propertyName events:
var people = new DefineList(["alice","bob","eve"]);
people.on("add", function(ev, items, index){
console.log("add", items, index);
}).on("remove", function(ev, items, index){
console.log("remove", items, index);
}).on("length", function(ev, newVal, oldVal){
console.log("length", newVal, oldVal);
})
people.pop(); // remove ["eve"] 2
// length 2 3
people.unshift("Xerxes"); // add ["Xerxes"] 1
// length 3 2
NOTE: Only changes made to indexed values using the list's set
method will dispatch change events.
👍 defineList.set(0, 'newValue'); // will dispatch event
👎 defineList[0] = 'newValue'; // will NOT dispatch event