Currently I have this function in backbone.
It update the model when onChange event is triggered.
bindElementToAttribute: function(el, name, eventType) {
var that = this;
eventType = typeof(eventType) != 'undefined' ? eventType : "change";
$(el).on(eventType, function() {
var obj = {};
obj[name] = $(el).val();
that.model.set(obj, {silent: true});
return true;
});
I'm using a datepicker component of react to add a date field in this model, but this function of backbone does not trigger the onChange event when I select the date. This is the component : https://github.com/Hacker0x01/react-datepicker
In my component, I manually triggered the 'change' event
handleChange(date) {
this.setState({
startDate: date
});
$('input[name=release_date]').trigger('change')
}
This is working fine, but when I select a new date in the datepicker, it pass the old value to the model. When onchange is triggered the value has not yet updated.
How can I fix this?
Thanks everyone
This is probably because you trigger the event before your component re rendered as a result of setState
, therefore you get the Dom's old value.
Two options to solve this:
1.You can pass setState a callback function as second parameter, like this:
this.setState({
startDate: date
}, function(){$('input[name=release_date]').trigger('change')});
the callback function will be executed once setState is completed and the component is re-rendered.(read more here: http://reactjs.cn/react/docs/component-api.html#setstate ).
2.And more React-ish- pass a callback function as prop to your component and execute it handleChange
instead of triggering an input
change. like this:
handleChange(date) {
this.setState({
startDate: date
});
this.prop.onChangeCallback(date);
}
* You can execute the onChangeCallback
, at specific points in your component's lifecycle. read about Lifecycle Methods to decide on which point.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.