Backbone.js - Where does this argument value come from?

I was not sure how to express my question in such a way that it became clear, so I created the diagram below. The example is specific to JavaScript and Backbone.js, but I assume that this can also be considered as just a general programming issue.

I have an example Backbone collection, and it's hard for me to understand how the values ​​are passed. I suggest that a “task” can easily be any arbitrary value, such as “taco” or “horse,” and work just as well. I’m just wondering where and how the “task” gets its value comparable to it.

This is how I view the problem, and I tried to recreate the path of my confusion below:

enter image description here

Here is the Task model, if that helps:

var Task = Backbone.Model.extend({ isComplete: function() { return this.get('completed_at') !== null; } }); 
+4
source share
2 answers

The comparator function is called with the underscore _.sortBy with an array element as an argument, there is a ton of object creation and iteration for what essentially boils down to a much faster native sort:

 someArrayOfTasks.sort( function( taskA, taskB ) { return taskA.dueDate < taskB.dueDate ? -1 : taskA.dueDate > taskB.dueDate ? 1 : 0; }); 

Or a simpler example:

 [3,2,5,1,4].sort( function(a,b){ return ab; }); //[1, 2, 3, 4, 5] [3,2,5,1,4].sort( function(a,b){ return ba; }); //[5, 4, 3, 2, 1] 

Here, the comparator function gets its arguments from the sort function when trying to resolve the sort order, the value that you return from the comparator determines in which order the array is sorted.

I would suggest normal sorting by cellular network, since it is 10 times faster for me in chrome and easier to understand, because the comparator function is actually ... compares: http://jsperf.com/underscore-sort-vs- normal-sort

+1
source

The comparator function of the collection takes the model as input. I think you need to write comparators, for example:

 function (task){ return task.get('dueDate'); } 

Note. Basic comparators are different from the usual JS array sorting comparator!

0
source

Source: https://habr.com/ru/post/1385019/


All Articles