KendoUI ComboBox Change Event Runs Multiple Times - javascript

I have an MVC Control for a KendoUI ComboBox that does NOT setup the Change Event ahead of time. Upon rendering, a page controller sets-up & shims-in its' own Change Event.
Oddly, this event gets called TWICE:
When I change the Selected Item
When I click away from the control
Q: What am I doing wrong?
Q: Is this HOW we should over-write the change event on an existing Kendo ComboBox?
MVC CONTROL:
As you can see, I am NOT defining any client-side events here...
#(Html.Kendo().ComboBox()
.Name("ddlTechnician")
.Filter("contains")
.Placeholder("Select Technician...")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new List<SelectListItem>() {
new SelectListItem() { Text = "Frank", Value = "1" },
new SelectListItem() { Text = "Suzie", Value = "2" },
new SelectListItem() { Text = "Ralph", Value = "3" }
})
.Suggest(true)
.HtmlAttributes(new { style = "width:300px;" }))
PAGE CONTROLLER:
And, I am only defining the event ONCE here. I have also confirmed the event isn't already firing BEFORE setting it in the Page Controller
$(document).ready(function () {
var PageController = (function ($) {
function PageController(options) {
var that = this,
empty = {},
dictionary = {
elements: {
form: null
},
instances: {
ddlTechnician: null
},
selectors: {
form: 'form',
ddlTechnician: '#ddlTechnician'
}
};
var initialize = function (options) {
that.settings = $.extend(empty, $.isPlainObject(options) ? options : empty);
dictionary.elements.form = $(dictionary.selectors.form);
// Objects
dictionary.instances.ddlTechnician = $(dictionary.selectors.ddlTechnician, dictionary.elements.form).data('kendoComboBox');
// Events
dictionary.instances.ddlTechnician.setOptions({ change: that.on.change.kendoComboBox });
};
this.settings = null;
this.on = {
change: {
kendoComboBox: function (e) {
// This is getting called MULTIPLE TIMES
console.log('kendoComboBox RAN');
}
}
}
};
initialize(options);
}
return PageController;
})(jQuery);
var pageController = new PageController({});
});

I was able to reproduce your problem on a Kendo JQuery Combobox when I set the event handler through setOptions, which is not the recommended way after the widget has been rendered. Instead you should use the "bind" method as shown in the documentation's example for change events.
Try changing the line of code where you set your event handler to this:
dictionary.instances.ddlTechnician.bind("change", that.on.change.kendoComboBox);
Here's a dojo that shows the difference: http://dojo.telerik.com/iyEQe
Hope this helps.

Related

Kendo Observable Change event

I have a kendo Obervable as follows:
var ViewModel = kendo.observable({
ID: 1,
TITLE: "SomeValue",
});
and then I have bound this as follows:
kendo.bind($(".bind-view"), ViewModel );
Now there is button on the page. When clicked I need to check if there are any changes to this ViewModel.
I have tried
$(".ClearAnalysisInfo").on('click', function (event) {
ViewModel.bind("change", function (e) {
//Some code
});
});
But I'm not able to get this ViewModel property whether it changed or not.
Binding the ObservableObject's change event of inside the button's click handler is too late. You need to do that immediately after the ObservableObject is created.
Inside the change handler, you will receive information about the changed field. Use this information to raise some JavaScript flag or save the details you need, so that you can use them later in the button's click handler.
var viewModelChanged = false;
var ViewModel = kendo.observable({
ID: 1,
TITLE: "SomeValue",
});
ViewModel.bind("change", function (e) {
viewModelChanged = true;
});
$(".ClearAnalysisInfo").on('click', function (event) {
if (viewModelChanged) {
// ...
}
});

Vue DevTools updating correctly but not browser window

I'm having a strange issue where the value found in Vue DevTools is correct. It's declared in my data as expected. The first time I click on "Edit" an item, the correct value shows up in my browser window as well.
However, if I click on "Edit" an item that has a different quantity, the same value shows up again even if it is incorrect (it should be prepopulating from the database).
Then, if I click back on the first "Edit" item again that value will get updated with the previous value!
The craziest part is that while my browser window is not showing the correct value, the correct result is showing up in Vue DevTools at all times! The circled item in the image below is the UUID for the "Quantity" of 100, which is the correct value. Yet 700 is showing up (the previous Edit item's value). Anybody ever had this happen before and know what gives?
Here's some snippets of relevant code (it's from a Vue component using vue-resource, and this is taking place in a bootstrap modal in a Laravel project):
Vue JS
data() {
return {
selected_options: {},
attributes: [],
}
},
methods: {
editLineItem: function (line_item) {
this.getProductOptionsWithAttributes(line_item.product_id);
this.getPrepopulatedOptionsForLineItem(line_item.id);
},
getProductOptionsWithAttributes: function (product_id) {
var local_this = this;
var url = '/api/v1/products/' + product_id + '/options';
this.$http.get(url).then(function (response) {
local_this.attributes.$set(0, response.data);
}, function (response) {
// error handling
});
},
getPrepopulatedOptionsForLineItem: function (id) {
var local_this = this;
var url = '/api/v1/line_items/' + id + '/options';
this.$http.get(url).then(function (response) {
Object.keys(response.data).forEach(function (key) {
Vue.set(local_this.selected_options, key, response.data[key]);
});
}, function (response) {
//#TODO Implement error handling.
});
},
}
HTML
<div v-for="(key, attribute) in attributes[0]" class="col-md-12 selectbox_spacing">
<label for="option_{{$index}}">{{key}}</label><br/>
<select class="chosen-select form-control" v-model="selected_options[key]" v-chosen="selected_options[key]" id="option_{{$index}}">
<option v-for="option in attribute" value="{{option.id}}">{{option.name}}</option>
</select>
</div>
<button v-on:click="editLineItem(line_item)">
Main.js vue-directive:
Vue.directive('chosen', {
twoWay: true, // note the two-way binding
bind: function () {
$(this.el)
.change(function(ev) {
// two-way set
//this.set(this.el.value);
var i, len, option, ref;
var values = [];
ref = this.el.selectedOptions;
if(this.el.multiple){
for (i = 0, len = ref.length; i < len; i++) {
option = ref[i];
values.push(option.value)
}
this.set(values);
} else {
this.set(ref[0].value);
}
}.bind(this));
},
update: function(nv, ov) {
// note that we have to notify chosen about update
$(this.el).trigger("chosen:updated");
}
});
var vm = new Vue({
el : '#wrapper',
components: {
LineItemComponent
}
});
Script in edit.blade.php file:
<script>
$(document).ready(function() {
$('#lineItemModal').on('shown.bs.modal', function () {
$('.chosen-select', this).chosen('destroy').chosen();
});
}
</script>
by default, custom directives have a priority of 1000. v-model has a priority of 800 meaning it's evaluated after v-chosen when the template is compiled.
My Assumption is now: this is also affecting the update.
What I mean by that: I think $(this.el).trigger("chosen:updated"); in the v-chosen update method is called before v-model did refresh the selected attribute on the list of <option> elements - and that's where chosen checks for the new selected value.
Long story short: try this:
Vue.directive('chosen', {
priority: 700, // Priority lower than v-model
twoWay: true, // note the two-way binding
bind: function () {
....

Pub/Sub scope in jQuery

I am attempting to implement a Pub/Sub pattern in jQuery with the following code :
$.each({
trigger : 'publish',
on : 'subscribe',
off : 'unsubscribe'
}, function ( key, val) {
jQuery[val] = function() {
o[key].apply( o, arguments );
};
});
This works fine until I attempt to build something with multiple instances.
I have an activity object that is applied to each $('.activity_radio') div element. When I click on a radio button inside any $('.activity_radio') div the $.subscribe event will trigger (X) amount of times based on the number of activity_radio divs on are on the page.
How do I publish/subscribe events based only within a particular div?
Code
Radio Activity ( radio-activity.js )
var activity = {
init : function ( element ) {
// get our boilerplate code
this.activity = new util.factories.activity();
this.element = element;
this.$element = $(element);
// other init code
// gather our radio elements
this.target_element = this.$elem.find('input[type=radio]');
// send our radio elements to onSelect
this.activity.onSelect(this.target_element);
// trigger click function that will subscribe us to onSelect publish events
this.click()
},
// subscribe to events
click : function()
{
$.subscribe('activity.input.select', function ( event, data ){
// we have access to the value the user has clicked
console.log(data);
// trigger another function // do something else
});
}
}
Base Activity Boilerplate Code ( activity-factory.js )
var activity_factory = factory.extend({
init: function(e)
{
// init code
},
onSelect : function ( inputs ) {
inputs.on('click', function(){
// do some processing
// retrieve the value
var data = $(this).val();
// announce that the event has occured;
$.publish( 'activity.input.select', data );
});
}
}
});
Triggered when DOM is ready
$(function(){
// foreach DOM element with the class of activity_radio
$('.activity_radio').each(function(){
// trigger the init func in activity object
activity.init(this);
});
});
You can write your subscribe/publish as a plugins
$.each({
trigger : 'publish',
on : 'subscribe',
off : 'unsubscribe'
}, function ( key, val) {
jQuery.fn[val] = function() {
this[key].apply(this, Array.prototype.slice.call(arguments));
};
});
And you will be able to call it on $element
this.$element.subscribe('activity.input.select', function(event, data) {
and
onSelect: function ( inputs ) {
var self = this;
inputs.on('click', function(){
// do some processing
// retrieve the value
var data = $(this).val();
// announce that the event has occured;
self.$element.publish('activity.input.select', data);
});
}

Javascript MVC Controller and Click Events

I'm having a problem with the click events not working using a Javascript MVC Controller.
TEST.Assignments.AssignmentsController = function (element) {
var elements = {
activeAssignmentsPanel: $('#lpn-activeAssignments_Cont'),
assignmentViewLink: $("#lpn-activeAssignments_Cont table tr th a")
};
var _this = this;
var model = new TEST.Assignments.AssignmentModel();
this.buildAssignmentsList = function () {
var assignments = model.getActiveAssignmentsList({
assignmentMode: "active",
mock: true,
success: function (data) {
dust.render("ActiveAssignmentsPanel", data, function(err, out) {
elements.activeAssignmentsPanel.append(out);
});
}
});
};
this.getAssignmentDetails = function(assignmentId) {
console.log(assignmentId);
};
//bind all events
elements.assignmentViewLink.click(function (e) {
console.log("blah");
console.log($(this).data("assignmentKey"));
});
};//end assignments controller
$(function () {
var assignmentsController = new TEST.Assignments.AssignmentsController();
assignmentsController.buildAssignmentsList();
});
If you look at the //bind events, I have a click function there that should be working. But it is not. The constructor is being called and the elements are traced out correctly. Any idea why the click event won't work?
I assume the assignmentViewLink elements are created and appended in the success callback. If so, it looks like a sequence problem. When you bind the click event, the assignmentViewLink elements have not been created yet, and hence, the click eventhandler isn't attached.
//bind all events
// assignmentViewLink is empty []
elements.assignmentViewLink.click(function (e) {
console.log("blah");
console.log($(this).data("assignmentKey"));
});
To verify this, move the elements.assignmentViewLink(...) into the success callback.

Replacing jQuery.bind with jQuery.on

I've written a program that includes a form that the user interacts with. Because there are lots of events bound to different buttons I have written a loop that parses some JS that contains the form input information. Here is some example data:
var value = 0,
forms = {
place_controls : {
attrs : {
'class' : 'place-form'
},
input : {
place_x : {
attrs : {
type : 'text',
},
events : {
change : function () {
value = 10;
}
}
},
place_y : {
attrs : {
type : 'text',
},
events : {
change : function () {
value = 50
}
}
}
}
}
}
The data is then parsed by this:
$.each(forms, function (form_index, form) {
var $form_markup = $('<form>').attr(form.attrs);
// Next: loop through each input element of the form we've reached
$.each(form.input, function (element_index, element) {
var $elem = $('<input>').attr(element.attrs);
$elem.appendTo($form_markup);
if (element.events !== undefined) {
$.each(element.events, function (event_index, event) {
$elem.bind(event_index, event);
//$form_markup.on(event_index, $elem, event);
});
}
});
$form_markup.appendTo($form_goes_here);
});
As you can see, I'm using .bind() at the moment, however I want to use .on(). Unfortunately, when I do this all of the items within a form are bound to the last event parsed by the function. When I use .bind() everything works as planned - i.e. Clicking on 'place_x' sets value to 10, clicking 'place_y' sets value to 50.
When using .on(), whichever I change sets value to 50, which I am assuming is because the last function is becoming bound to each event.
Can anybody see what I have done wrong?
Update: There are many different ways to do this, and I have subsequently changed how my code works, however this question is related to why .bind() is working and why .on() is not.
//$elem.bind(event_index, event);
//It looks like you should just be using .on() like this
$elem.on(event_index, event);
The way it looks like you are trying to use .on() is in the live -bubbling- event sort of way, it looks like only the last event you are created is sticking, why each value just gets set to 50.
//$form_markup.on(event_index, $elem, event);
You can create elements with property maps that include handler functions in one simple call:
var $elem = $('<input/>', properties);
The "properties" object can contain event handlers:
var $elem = $('<input/>', {
type: 'text',
name: 'somethingUseful',
click: function(ev) { /* click handler */ },
change: function(ev) { /* change handler */ },
css: { color: "red" }
});

Categories

Resources