I am trying to a custom binding to input as datepicker:
CODE HERE: http://sdrv.ms/Xc5HZw
I have the following code in place but the validation doesn't highlight the control when its invalid:
ko.bindingHandlers.datepicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
// code here
ko.bindingHandlers.validationCore.init(element, valueAccessor, allBindingsAccessor);
},
update: function (element, valueAccessor) {
// code here
}
};
I have a very similar problem... the minute i add ko.validation.js
both the init: function and update are skipped over.... nothing inside the function fires....
are you at least hitting the ko.bindingHandlers.validationCore method?
Related
In our application we have more than 100 grids and we need to display help button on Title bar of grid, for that I have created a plugin using
$.jgrid.extend({
EnableHelpButton: function(value) {
var $t = this;
...............;
}
});
Currently, I go to each .html page of grid and need to call the EnableHelpButton as shown in below code.
-----------------Index1.html-------------------------
$("#TestGrid1").bind("jqGridInitGrid", function () {
$(this).EnableHelpButton(true);
});
-----------------Index2.html-------------------------
$("#TestGrid2").bind("jqGridInitGrid", function () {
$(this).EnableHelpButton(true);
});
How I can create a generic way to call this EnableHelpButton on jqGridInitGrid events of each grid. It should write once on single place and it should work for each grid.
You have to have some specific call of your custom function on every page. One way will be to define you plugin so
$.jgrid.extend({
EnableHelpButton: function(value) {
var $t = this;
...............;
},
myInit: function () {
return this.each(function () {
$(this).bind("jqGridInitGrid", function ({
$(this).EnableHelpButton(true);
});
});
}
});
Even in the case you need to include .jqGrid("myInit") call on every page. You can make the call of myInit before the <table> is converted to grid. For example instead of
$("#grid").jqGrid({
... // parameter used to create jqGrid
});
you will be use now
$("#grid").jqGrid("myInit").jqGrid({
... // parameter used to create jqGrid
});
Only if you never use onInitGrid callback in any your grids you can use the callback instead of jqGridInitGrid. In the case you need just define the callback in some JavaScript code which you included in every your page:
$.extend(true, $.jgrid.defaults, {
onInitGrid: function () {
$(this).EnableHelpButton(true);
}
});
In the way you will set default implementation of onInitGrid for every grid.
Thus the definition of common initialization inside of onInitGrid callback produces the shortest implementation, but have restriction that you shouldn't use the callback in no of your grids. Alternatively you defines the method myInit which makes all bindings add you can add .jqGrid("myInit") on every your grids. The last approach will work for every jqGrid.
For a quick view of my problem I have made a working jsFiddle here:
In KnockoutJS I have made a custom extender validator to test if the input format is in the HHMM format. If it is it returns the new value, if it doesn't it will set it back to the old value this is currently working.
ko.extenders.acValidTimeHHMM = function (target, options) {
var result = ko.computed({
read: target,
write: function (newValue) {
var re = /^([0-9]|0[0-9]|1[0-9]|2[0-3])[0-5][0-9]$/;
if (!re.test(newValue)) {
target.notifySubscribers(target());
//Time not in correct format return old time
return;
}
target(newValue);
}
}).extend({ notify: 'always' });
result(target());
return result;
};
The problem I am having is that I update my database when the value changes using a computed. However this is also firing when I reset the value back to its original using my validator. (Method based on Ryan Rahlf dirty flag technique here )
self.update = ko.computed(function () {
self.timeOne();
self.timeTwo();
alert("Fired");
});
The problem is obviously the line target.notifySubscribers(target()); in my validator. However without this line I can't reset the value to its old value and I can't find another way to do this.
So this only fires when a value actually changes rather then the validator resetting it. The jsFiddle demonstrates my problem exactly and can be used to make a working version (hopefully) I know its currently firing on page load too.
The problem I am having is that I update my database when the value changes using a computed.
I don't know all your logic, but I don't think this is a good idea to update the db each time your knockout view model has updated. May be you should look at knockout validation plugin. Using this plugin you can build the same custom validation rule and update the db only on form submit event.
About your problem...
The simplest solution I'm found is to send a success callback function to the validation extension like an option.
Something like this.
JS:
var ViewModel = function() {
var update = function () {
alert("value was successfully changed");
};
var cancel = function () {
alert("validation failed. previous value was returned");
};
var timeOne = ko.observable("1100").
extend({
acValidTimeHHMM: {
success: update,
fail: cancel
}
});
var timeTwo = ko.observable("1248").
extend({ acValidTimeHHMM: { success: update } });
return {
timeOne: timeOne,
timeTwo: timeTwo
};
};
ko.extenders.acValidTimeHHMM = function(target, option) {
var baseOptions = {
success: null,
fail: null
};
$.extend(baseOptions, option);
var result = ko.computed({
read: target,
write: function (newValue) {
var oldValue = target();
if(newValue == oldValue) return;
var re = /^([0-9]|0[0-9]|1[0-9]|2[0-3])[0-5][0-9]$/;
if (!re.test(newValue)) {
target.notifySubscribers(oldValue);
if(typeof(baseOptions.fail) == "function")
baseOptions.fail();
return;
}
target(newValue);
if(typeof(baseOptions.success) == "function")
baseOptions.success()
}
}).extend({ notify: 'always' });
result(target());
return result;
};
ko.applyBindings(new ViewModel());
HTML:
<p>Time One<input data-bind='value: timeOne' /></p>
<p>Time Two<input data-bind='value: timeTwo' /></p>
Can't figure out what's wrong. When I click on a model title, it fetches all models in collection at once rather than fetch one model. If I move this event from logView to logsView it works properly but doesn't have access to model, well I can find this model using index or ant other model's ID but don't think this is a nice way.
var Log = Backbone.Model.extend({});
window.LogsList = Backbone.Collection.extend({
model:Log,
url:function (tag) {
this.url = '/logs/' + tag;
return this;
}
});
window.colList = new LogsList();
window.logView = Backbone.View.extend({
el:$('.accordion'),
template:_.template($('#log').html()),
initialize:function () {
this.model.bind('add', this.render, this);
},
events:{
"click .accordion-toggle" :"getLogBody"
},
render:function () {
return this.template(this.model.toJSON());
},
getLogBody:function () {
this.model.fetch();
}
});
window.LogsView = Backbone.View.extend({
el:$("#content"),
initialize:function (options) {
colList.bind('reset', this.addAll, this);
colList.url(options.data).fetch();
},
addOne:function (model) {
var view = new logView({model:model});
$("#accordion").append(view.render());
},
addAll:function () {
colList.each(this.addOne);
}
});
window.listView = new LogsView({data:"Visa_Cl"});
The problem is caused by your el in the LogView: el:$('.accordion')
Backbone's view events are scope to the view's el. In this case, you've specified the view's el as ALL HTML elements with a class of "accordion". Therefore, when you click on any of your HTML elements with this class, the code runs for all of them, which is why you are seeing this behavior.
This article will show you a few options for doing what you want, correctly:
Backbone.js: Getting The Model For A Clicked Element
I would also recommend reading this one, to better understand the use of el in Backbone, and a few of the tricks and traps of it:
Backbone.js: Object Literals, Views Events, jQuery, and el
Serverside I render a hiddenfield, I then use a jquery widget called flexbox to create a combobox, it creates a input element client side and copies the selected ID (Not text) to the hidden field once you select something in the box.
The problem is that the validation code adds a classname to the hiddenfield when something is wrong with validation, I want it to be added to the input element, can I somehow listen to when the classname is added, or somehove hook into the event and move the classname to the inputfield.
This works but its ugly as hell, would like a better solution
var oldClass = $hdn.attr('class');
setInterval(function () {
if (oldClass != $hdn.attr('class')) {
$input.removeClass(oldClass);
oldClass = $hdn.attr('class');
$input.addClass($hdn.attr('class'));
}
}, 200);
Thanks.
Where I have a hidden element being validated, I add a custom attribute, data-val-visibleid. Then, in jquery.validate.js, I modify the highlight and unhighlight functions by adding the following at the end of both functions:
if ($(element).is(":hidden")) {
var targetId = $(element).attr("data-val-visibleid");
$("#" + targetId).addClass(errorClass).removeClass(validClass);
}
Some people do not like to meddle in jquery.validate.js, but it is usually the easiest method to achieve customizations like this.
UPDATE
I did some research, and discovered that jquery.validate has a nifty setDefault method, where you can override the default functions, such as highlight() and unhighlight. Add the following to your page after the other scripts have been loaded:
$.validator.setDefaults( {
highlight: function (element, errorClass, validClass) {
$(element).addClass(errorClass).removeClass(validClass);
if ($(element).is(":hidden")) {
var targetId = $(element).attr("data-val-visibleid");
$("#" + targetId).addClass(errorClass).removeClass(validClass);
}
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass(errorClass).addClass(validClass);
if ($(element).is(":hidden")) {
var targetId = $(element).attr("data-val-visibleid");
$("#" + targetId).addClass(errorClass).removeClass(validClass);
}
}
});
This will override the default functions, without changing the underlying script.
Thanks to Counsellorben i found a good solution, I did it in a slightly different way though.
First i override the default methods in my master object contructor which is is constructed at document.ready. document.ready is however too late and your methods will not trigger when doing a triggering validation from form.valid() it will however trigg when doing a submit (very strange) this code works both for submit and triggered from script
(function() {
var highlight = $.validator.defaults.highlight;
var unhighlight = $.validator.defaults.unhighlight;
$.validator.setDefaults({
highlight: function (element, errorClass, validClass) {
if ($(element).attr("data-val-visualId") != null) {
element = $("#" + $(element).attr("data-val-visualId"))[0];
}
highlight(element, errorClass, validClass);
},
unhighlight: function (element, errorClass, validClass) {
if ($(element).attr("data-val-visualId") != null) {
element = $("#" + $(element).attr("data-val-visualId"))[0];
}
unhighlight(element, errorClass, validClass);
}
});
})();
I found both these answers to be very helpful and just wanted to add for anyone using version 1.9.0 of the Validation plugin that you will need to override the default behavior that ignores hidden fields as detailed in this other post: jQuery Validate - Enable validation for hidden fields
I have a multiple files uploadify setting with:
'onComplete' : function(event, ID, fileObj, response, data) {
myCollection.add({params parsed from response json});
}
which triggers (trough this.collection.bind('add', this.add)) this collection view method:
add: function(obj) {
var view = new MyModelView({model: obj});
this.$('.insert-models-here').append(view.render().el);
return this;
},
The new MyModelView call triggers: MyModelView::initialize() which is here:
initialize: function() {
var t = $('#photo-template').html();
this.template = _.template(t);
this.model.view = this;
},
And every _.template() calls jumps inside __flash__toXML() method from which all thread is stopped.
The result is no model added inside my collection from any uploadify event.
Does anyone knows why and how to avoid this?
Ok, I found solution.
Problem was in using underscore in uploadify events so I replace underscore _.templates with icanhaz and rewrite my add() collection view method this way to workaround any underscore functionality:
add: function(obj) {
var view = new MyModelView({model: obj});
$('.insert-models-here').first().append(view.render().el);
return this;
},
Hope someone will call my name in future..