Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
100
rated 0 times [  102] [ 2]  / answers: 1 / hits: 6634  / 11 Years ago, thu, february 13, 2014, 12:00:00

I have set up the following select for changing semesters on page. When the select detects a change, the changeSemesters function is fired, which runs an AJAX that replaces the current data on the page with data specific to the selected semester.



View



<select data-bind=options: semestersArr, optionsText: 'name', optionsValue: 'id', value: selectedSemester, event: { change: changeSemesters }></select>


ViewModel



this.selectedSemester = ko.observable();

//runs on page load
var getSemesters = function() {
var self = this, current;

return $.get('api/semesters', function(data) {
self.semestersArr(ko.utils.arrayMap(data.semesters, function(semester) {
if (semester.current) current = semester.id;
return new Model.Semester(semester);
}));

self.selectedSemester(current);
});
};

var changeSemesters = function() {
// run ajax to get new data
};


The problem is that the change event in the select fires the changeSemester function when the page loads and sets the default value. Is there a way to avoid that without the use of a button?


More From » knockout.js

 Answers
3

Generally what you want to do in these scenarios is to use a manual subscription, so that you can react to the observable changing rather than the change event. Observables will only notify when their value actually changes.



So, you would do:



this.selectedSemester.subscribe(changeSemesters, this);


If selectedSemester is still changing as a result of getting bound, then you can initialize it to the default value.



this.selectedSemester = ko.observable(someDefaultValue);

[#47761] Wednesday, February 12, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jocelynkarsynr

Total Points: 472
Total Questions: 98
Total Answers: 96

Location: Macau
Member since Mon, Nov 16, 2020
4 Years ago
jocelynkarsynr questions
Tue, Feb 8, 22, 00:00, 2 Years ago
Sat, Jul 11, 20, 00:00, 4 Years ago
Sun, May 10, 20, 00:00, 4 Years ago
Sat, Jan 18, 20, 00:00, 4 Years ago
;