Chris Schmitz Chris Schmitz - 6 months ago 15
Javascript Question

Extjs bound html not updating when viewmodel data is changed

I have a view that has the html config bound to data within my viewmodel.

The view



Ext.define('MyApp.MyView',{
extend: 'Ext.Panel',
renderTo: Ext.getBody(),
height: 300,
controller: 'myviewcontroller',
viewModel:{
type: 'myviewmodel'
},

title: 'Testing formula updates',
bind:{
html: 'Date: <b>{selectedDate}</b>, <br />Month: <b>{currentMonth}</b>'
},

bbar:[
{xtype: 'button', text: 'Increment Month', handler: 'onIncrementMonth'}
]
});


The ViewModel



Ext.define('MyApp.MyViewModel',{
extend: 'Ext.app.ViewModel',
alias: 'viewmodel.myviewmodel',

data:{
selectedDate: new Date()
},
formulas:{
currentMonth: function (get){
var monthNames = ["January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"];
var monthNumber = get('selectedDate').getMonth();
return monthNames[monthNumber];
}
}

});


When the view is initially rendered, the bound data populates into the HTML config as expected.

I then created a method in my viewcontroller to increment the date.

The ViewController



Ext.define('MyApp.MyViewController',{
extend: 'Ext.app.ViewController',
alias: 'controller.myviewcontroller',

onIncrementMonth: function (){
var vm = this.getViewModel();
var dateChange = vm.get('selectedDate');

dateChange.setMonth(dateChange.getMonth() + 1);

vm.set('selectedDate', dateChange);
}
});


I'm sure this is leading to a facepalm moment, but I was expecting that when I update the
selectedDate
data in my viewmodel, it should trigger both bound pieces of my html config to update, but it's not.

The viewmodel data is definitely updating. If you inspect the
dateChange
variable in the viewcontroller when you click the increment button the second time you'll see that the date has indeed increased.

Is there something I'm missing as far as getting my bound config to update?

I have this here in a fiddle.

Answer

Once I changed the line:

vm.set('selectedDate', dateChange);

To:

vm.set('selectedDate', new Date(dateChange));

It works.

Comments