Learning BackboneJS and javascript and I am stuck with one issue. I have one graph in my hompage and one dropdown. I want to make sure the graph gets refreshed as per the dropdown option selected. But I just want the graph to get refreshed not the dropdown. With my current design entire page gets refreshed. Below is what I have tried till now. I think I have not structured my code properly.
Model for graph data in backbone:
define(['backbone'], function(Backbone) {
// creating model
var chart = Backbone.Model.extend({
urlRoot: 'http://localhost:51349/SMS_Rest.svc/v1/Starter',
initialize: function() {
},
fetch: function(data) {
var d = $.Deferred();
var self = this;
var ajaxRequest = $.ajax({
url: this.urlRoot,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(data)
});
ajaxRequest.done(function(json) {
// SOME STUFF
d.resolve();
});
return d.promise();
}
});
return {
chart: chart
};
});
Model for dropdown data
define(['backbone'], function(Backbone) {
var dropdownModel = Backbone.Model.extend({
urlRoot: 'http://localhost:51349/SMS_Rest.svc/v1/dropdown',
initialize: function() {
},
fetchDropdown: function(data) {
var self = this;
var d = $.Deferred();
var dropdownRequest = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: this.urlRoot,
data: JSON.stringify(data)
});
dropdownRequest.done(function(data) {
console.log(data);
self.set({
dropdownData: data
});
d.resolve();
});
return d.promise();
}
});
return {
dropdownModel: dropdownModel
};
});
Controller for dropdown model and graph model:
define(['backbone', 'firstSubViewModel', 'dashboardModel', 'dropdownViewModel', 'dropdownModel'],
function(Backbone, firstSubViewModel, dashboardModel, dropdownViewModel, dropdownModel) {
// CONTROLLER FOR GRAPH DATA
var ch = new dashboardModel.chart({});
if (localStorage.getItem('p_kt')) {
var data = {
tokenProp: localStorage.getItem('p_kt'),
};
$.when(
ch.fetch(data)
).then(function() {
new firstSubViewModel({
el: '#chartAnchor1',
model: ch
});
});
} else {
console.log('Storage is null');
window.location = "../index.html";
}
//CONTROLLER FOR DROPDOWN
var dropdownModel = new dropdownModel.dropdownModel({});
$.when(
dropdownModel.fetchDropdown(data) // fetched data from MODEL REST Service
).then(function() {
new dropdownViewModel({
el: '#drilldown2',
model: dropdownModel
});
});
});
Now when user selects any option from the dropdown the text in the dropdown gets updated accordingly and I need to (obviously) call this controller to get newly rendered graph. But this controller also has controller for loading "DROPDOWN" so everything works totally fine but dropdown element also gets loaded again and thus text in the dropdown vanishes. Please guide me. How to code my controller so that I can just call the graph model and not the dropdown model so that the text of dropdown remains intact OR I need to change the way I have coded my controller.