Knockout.js binding with multiple Select2 - javascript

My Question is when ever I bind my Select2 with Multiple with Knockout View Model. After selecting one of the options, the data is lost for the second time
KnockOutCode
$(window).load(function () {
ko.bindingHandlers.select2 = {
init: function (element, valueAccessor, allBindingsAccessor) {
var obj = valueAccessor(),
allBindings = allBindingsAccessor(),
lookupKey = allBindings.lookupKey;
$(element).select2(obj);
if (lookupKey) {
var value = ko.utils.unwrapObservable(allBindings.value);
$(element).select2('data', ko.utils.arrayFirst(obj.data.results, function (item) {
return item[lookupKey] === value;
}));
}
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).select2('destroy');
});
},
update: function (element) {
$(element).trigger('change');
}
};
ko.applyBindings(new ViewModel());
function ViewModel() {
var self = this;
self.MetricsModel = ko.observableArray([]);
GetMetrics();
function GetMetrics() {
$.ajax({
url: '/Admin/GetMetrics',
type: "POST",
dataType: "json",
success: function (returndata) {
self.MetricsModel(returndata);
},
error: function () {
alert("eRROR GET Applications");
}
});
};
}
$("#application-select-metrics").select2();
}
HTML File
<select multiple="multiple" id="application-select-metrics" class="form-control" data-bind="options: MetricsModel, optionsText: 'Metrics_Name', OptionsValue:'Metrics_ID', optionsCaption: 'Choose...', select2: {}"></select>
#*<select multiple="multiple" id="application-select-metrics" class="form-control">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>*#
Please note that the commented sections, i.e, hardcoded values works, and it allows me to select multiple values, and using Knockout it works for the first time, i get a list populated, but after selecting once, for the second time the data is lost.
Please help,
Thanks,
EDIT:
As mentioned by Hanes, I've edited the code, and introduced custom binding, but still it does not work, I dont think the update section of the custom binding is working properly,as the drop down populate once but fails to bind for the second time. Any help would be gladly appreciated.

#rniemeyer threw this up on a JSFiddle not too long ago that should help you out:
http://jsfiddle.net/rniemeyer/R8UF5/
His fiddle, updated
Use the following binding combined with a couple fiddles for when a value is updated:
ko.bindingHandlers.select2 = {
init: function(element, valueAccessor, allBindingsAccessor) {
var obj = valueAccessor(),
allBindings = allBindingsAccessor(),
lookupKey = allBindings.lookupKey;
setTimeout(function() {
$(element).select2(obj);
}, 0);
if (lookupKey) {
var value = ko.utils.unwrapObservable(allBindings.value);
$(element).select2('data', ko.utils.arrayFirst(obj.data.results, function(item) {
return item[lookupKey] === value;
}));
}
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).select2('destroy');
});
},
update: function(element) {
$(element).trigger('change');
}
};

First, in response to the comments: your code was correct. The JSFiddle done by Jeroen introduced the error in the mocked ajax call: he returned an array of ints, not of objects with the correct attributes. The problem only occurs when the select2 is applied.
Cause
You're applying select2, but select2 is not playing nice with Knockout. And why should it? It doesn't know anything about Knockout and your viewmodel, and it doesn't know how to play nice with it.
Solution
You need a knockout custom binding for the select2 control. A knockout custom binding is the way to create integration between your Knockout code and 3rd party plugins. To write and explain such a custom binding for you would be a bit too much for this answer, so instead I'll give you the following link:
https://github.com/ivaynberg/select2/wiki/Knockout.js-Integration
There's a solution that will help you fix the problem. They also link to a JSFiddle, and all in all you should be able to find all you need there. If this one is too complex for you, you might try googling 'select2 knockout custom binding' and see if you can find something less complex.
A reference to the concept of Knockout custom bindings: http://knockoutjs.com/documentation/custom-bindings.html
Good luck!

Related

Knockout binding and CK Editor toolbar not appearing

I am totally new to knock-out custom binding, I am trying to integrate ckeditor with knock-out biding, I have the following binding got from Google search,
ko.bindingHandlers.wysiwyg = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor();
var valueUnwrapped = ko.unwrap(value);
var allBindings = allBindingsAccessor();
var $element = $(element);
$element.attr('contenteditable', true);
if (ko.isObservable(value)) {
var isSubscriberChange = false;
var isEditorChange = true;
$element.html(value());
var isEditorChange = false;
$element.on('input, change, keyup, mouseup', function () {
if (!isSubscriberChange) {
isEditorChange = true;
value($element.html());
isEditorChange = false;
}
});
value.subscribe(function (newValue) {
if (!isEditorChange) {
isSubscriberChange = true;
$element.html(newValue);
isSubscriberChange = false;
}
});
}
}
}
I have the following code to bind,
$(function () {
$.getJSON("/getdata", function (data) {
ko.applyBindings({
testList: [{
test: ko.observable()
},
{
test: ko.observable()
}]
}, document.getElementById('htmled'));
});
});
HTML as follows
<div id="htmled" data-bind="foreach:testList">
Data
<div class="editor" data-bind="wysiwyg: test">Edit this data</div>
</div>
The binding works and show the toolbar when I call the ko.applyBindings outside the $.getJSON method. But when I call applyBindings inside, the toolbars not appearing. Can any body help me on this? I must be missing something for sure, any help on this is greatly appreciated.
Jsfiddle Added
Working :http://jsfiddle.net/jogejyothish/h4Lt3/1/
Not Working : http://jsfiddle.net/jogejyothish/Se8yR/2/
Jyothish
What's happening is this:
Your page loads with the single div. KO has yet to be applied to this div.
document.ready() fires. The CKEditor script applied CKEditor to any matching divs (none).
You make your ajax call.
The Ajax call completes. You apply bindings.
KO inserts two new divs, neither of which has CKEditor.
In order to fix it, you need to add some code inside your ajax success function to manually initialise the CKEditors, like:
$(".editor").each(function(idx, el) {
CKEDITOR.inline(el)
});
Here it is, working in your fiddle:
http://jsfiddle.net/Se8yR/5/
The reason your working version works is because the bindings are applied in document.ready, so KO renders the two div elements in time, and the CKEditor is successfully applied to them.
CKEditor takes some time to load.
In your first example, it loads after ko applies, which works fine.
In the second example, it loads before ko applies. The problem is that CKEditor looks for the contenteditable attribute which you set with ko, so the editor is not created.
You can create it manually with:
CKEDITOR.inline(element).setData(valueUnwrapped || $element.html());
Doc
Demo

Applying jquery plugin (selectric) to ko-bound dropdown

I'm building a simple query interface for a table of data.
I have two dropdowns - one to select the field from the table, and one to select the query to perform on that field. The query dropdown items depend on the data type, so I have to wait until the field is selected to populate it.
All the bindings work if I use plain old select elements. But I want to apply the selectric plugin to them. Problem is, after calling $(element).selectric() on the elements, I don't know how to get it to "refresh" the items - so only the first dropdown contains the bound elements because it's initially populated. The second one never seems to get the updated 'query' elements.
I've tried using a custom ko binding, and calling .selectric() on the update like so:
ko.bindingHandlers.selectric = {
init: function(element, valueAccessor)
{
$(element).selectric();
},
update: function(element, valueAccessor)
{
$(element).selectric();
}
};
Here's my bindings for the two drop downs:
<select data-bind="options: $parent.fields,
optionsCaption: 'Select field...',
value: field_name,
event: { change: fieldSelected },
selectric: {}"></select>
<select data-bind="options: queries,
optionsCaption: 'Select query...',
selectric: queries"></select>
Here's the fiddle w/ viewmodel, etc. http://jsfiddle.net/rUNJY/12/. If you disable the selectric binding, it will work... how can I get the plugin to re-create the dropdown with updated items?
There are many ways to do this. Here are two:
1) Listen to the observable specified in your binding. This same as your way.
Usage:
<select data-bind="options: queries,
optionsCaption: 'Select query...',
selectric: queries"></select>
Code:
ko.bindingHandlers.selectric = {
update: function(element, valueAccessor)
{
ko.unwrap(valueAccessor()); //must use value in order for update to be called
$(element).selectric('refresh'); //must specify that plugin should refresh. See selectric documentation
}
};
Sample: http://jsfiddle.net/p4X4j/
2) Use the observable specified in the options binding. I prefer this solution since I don't need to specify the same observable in two bindings.
Usage:
<select data-bind="options: queries,
optionsCaption: 'Select query...',
selectric: {}"></select>
Code:
ko.bindingHandlers.selectric = {
init: function (element, valueAccessor, allBindingsAccessor) {
$(element).selectric('');
if(allBindingsAccessor().options.subscribe) {
var optionsSubscription = allBindingsAccessor().options.subscribe(function (newValue) {
$(element).selectric('refresh');
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
optionsSubscription.dispose();
});
}
}
};
Sample: http://jsfiddle.net/LbRGz/1/

TinyMCE with knockout data binding would´t update

I have the TinyMCE WYSiWYG Editor presenting text depending on a selected object, but experience problem with the binding.
The first "instanciation" seems to work, but when choosing a new text from the drop down list of available text the editor goes blank and Firebug console tells me:
TypeError: D.hasChildNodes is not a function
...ute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r...
and
NS_ERROR_UNEXPECTED: Unexpected error
.../,"$1"));return false}});if(!u.getParam("accessibility_focus")){g.add(i.add(k,"a...
I have tried to recreate my code here: http://jsfiddle.net/xc4sz/1/
It´s not 100% but at least it does´t work. ;)
If I instead of clicking directly from text 1 to text 2 go via the "Choose option" the text is presented properly.
I guess it has to do with the "init" section below:
ko.bindingHandlers.tinymce = {
init: function (element, valueAccessor, allBindingsAccessor, context) {
var options = allBindingsAccessor().tinymceOptions || {};
var modelValue = valueAccessor();
var value = ko.utils.unwrapObservable(valueAccessor());
var el = $(element)
//handle edits made in the editor. Updates after an undo point is reached.
options.setup = function (ed) {
console.log(ed)
ed.onChange.add(function (ed, l) {
if (ko.isWriteableObservable(modelValue)) {
modelValue(l.content);
}
});
};
//handle destroying an editor
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
setTimeout(function () { $(element).tinymce().remove() }, 0)
});
//$(element).tinymce(options);
setTimeout(function () { $(element).tinymce(options); }, 0);
el.html(value);
},
update: function (element, valueAccessor, allBindingsAccessor, context) {
var $element = $(element),
value = ko.utils.unwrapObservable(valueAccessor()),
id = $element.attr('id');
//handle programmatic updates to the observable
// also makes sure it doesn't update it if it's the same.
// otherwise, it will reload the instance, causing the cursor to jump.
if (id !== undefined) {
var tinymceInstance = tinyMCE.get(id);
if (!tinymceInstance)
return;
var content = tinymceInstance.getContent({ format: 'raw' });
if (content !== value) {
$element.val(value);
//this should be more proper but ctr+c, ctr+v is broken, above need fixing
//tinymceInstance.setContent(value,{ format: 'raw' })
}
}
}
};
Depending on the versions of TinyMCE and jQuery that you are dependent on, you might like to try the custom binding I've recently rolled myself.
It's available on GitHub and NuGet
I found the issue. What happened was this:
you select Textbatch #1 and make some changes
you switch to Textbatch #2
the binding changes correctly from Textbatch #1 to #2
THEN the ed.onChange.add event handler kicks in and overwrites the content of the previous Textbatch #1 with that of the new Textbatch #2
Take a look at this updated fiddle (remove /show/light from the URL to get back to the editor). I had to inline select2.js, because Github does not allow files it hosts to be included remotely, causing your fiddle to fail.
The important part is in ko.utils.domNodeDisposal.addDisposeCallback:
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).tinymce().onChange.remove(changeHandler);
setTimeout(function () { $(element).tinymce().remove() }, 0)
});
I do not know why the removal of the editor is minimally delayed with a 0-second timeout, but there is probably a good reason for that. So all we do is remove the 'change' handler, so that the old editor cannot update the bound valueAccessor in your viewmodel anymore.
EDIT: I just noticed that I fixed your fiddle, but not necessarily your original exception… here is to hoping that the two were related.

knockout data-bind on dynamically generated elements

How is it possible to make knockout data-bind work on dynamically generated elements? For example, I insert a simple html select menu inside a div and want to populate options using the knockout options binding. This is what my code looks like:
$('#menu').html('<select name="list" data-bind="options: listItems"></select>');
but this method doesn't work. Any ideas?
If you add this element on the fly after you have bound your viewmodel it will not be in the viewmodel and won't update. You can do one of two things.
Add the element to the DOM and re-bind it by calling ko.applyBindings(); again
OR add the list to the DOM from the beginning and leave the options collection in your viewmodel empty. Knockout won't render it until you add elements to options on the fly later.
Knockout 3.3
ko.bindingHandlers.htmlWithBinding = {
'init': function() {
return { 'controlsDescendantBindings': true };
},
'update': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
element.innerHTML = valueAccessor();
ko.applyBindingsToDescendants(bindingContext, element);
}
};
Above code snippet allows you to inject html elements dynamically with the "htmlWithBinding" property. The child elements which are added are then also evaluated... i.e. their data-bind attributes.
rewrite html binding code or create a new. Because html binding prevents "injected bindings" in dynamical html:
ko.bindingHandlers['html'] = {
//'init': function() {
// return { 'controlsDescendantBindings': true }; // this line prevents parse "injected binding"
//},
'update': function (element, valueAccessor) {
// setHtml will unwrap the value if needed
ko.utils.setHtml(element, valueAccessor());
}
};
For v3.4.0 use the custom binding below:
ko.bindingHandlers['dynamicHtml'] = {
'update': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
// setHtml will unwrap the value if needed
ko.utils.setHtml(element, valueAccessor());
ko.applyBindingsToDescendants(bindingContext, element);
}
};
EDIT: It seems that this doesn't work since version 2.3 IIRC as pointed by LosManos
You can add another observable to your view model using myViewModel[newObservable] = ko.observable('')
After that, call again to ko.applyBindings.
Here is a simple page where I add paragraphs dynamically and the new view model and the bindings work flawlessly.
// myViewModel starts only with one observable
var myViewModel = {
paragraph0: ko.observable('First')
};
var count = 0;
$(document).ready(function() {
ko.applyBindings(myViewModel);
$('#add').click(function() {
// Add a new paragraph and make the binding
addParagraph();
// Re-apply!
ko.applyBindings(myViewModel);
return false;
});
});
function addParagraph() {
count++;
var newObservableName = 'paragraph' + count;
$('<p data-bind="text: ' + newObservableName + '"></p>').appendTo('#placeholder');
// Here is where the magic happens
myViewModel[newObservableName] = ko.observable('');
myViewModel[newObservableName](Math.random());
// You can also test it in the console typing
// myViewModel.paragraphXXX('a random text')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.1/knockout-min.js"></script>
<div id="placeholder">
<p data-bind="text: paragraph0"></p>
</div>
<a id="add" href="#">Add paragraph</a>
It's an old question but here's my hopefully up-to-date answer (knockout 3.3.0):
When using knockout templates or custom components to add elements to prebound observable collections, knockout will bind everything automatically. Your example looks like an observable collection of menu items would do the job out of the box.
Based on this existing answer, I've achived something similar to your initial intentions:
function extendBinding(ko, container, viewModel) {
ko.applyBindings(viewModel, container.children()[container.children().length - 1]);
}
function yourBindingFunction() {
var container = $("#menu");
var inner = $("<select name='list' data-bind='options: listItems'></select>");
container.empty().append(inner);
extendBinding(ko, container, {
listItems: ["item1", "item2", "item3"]
});
}
Here is a JSFiddle to play with.
Be warned, once the new element is part of the dom, you cannot re-bind it with a call to ko.applyBindings- that is why I use container.empty(). If you need to preserve the new element and make it change as the view model changes, pass an observable to the viewModel parameter of the extendBinding method.
Checkout this answer: How do define a custom knockout 'options binding' with predefined Text and Value options
ko.applyBindingsToNode is particularly useful.

Knockout Validation and Qtip

I currently use Jquery Validation and Qtip together to deal with the actual validation and displaying of information to the screen using the nice tooltip style notifications upon validation errors using the errorPlacement component of the validation options.
Currently each viewModel has its own custom method for setting up and kicking off the validation and callbacks, however I was trying to look at a nicer way of doing this, be it adding a custom binding to setup my validation rules via the data-bindings or an alternative way, but still yielding the same results (i.e the errorPlacement is triggered when a validation error occurs and tells Qtip to display the error for the given element).
Now before I started making one myself I just checked online and found Knockout Validation, which I initially thought was a great idea, I could apply my validation logic directly to the data within my viewModel and then just find some sort of callback to get Qtip to kick in, however it seems there is no callback that I can find documented. The library seems to do everything I want for the validation side of things, just not for the displaying side of things. I looked through the source code and examples but couldn't see anything other than ko.validation.group(viewModel) which would give me an observable containing the errors, but I am not sure if I could use this the same way as I was expecting.
Here is an example of how my current validation happens:
/*globals $ ko */
function SomeViewModel() {
this.SetupValidation = function () {
var formValidationOptions = {
submitHandler: self.DoSomethingWhenValid,
success: $.noop,
errorPlacement: function (error, element) {
if (!error.is(':empty'))
{ qtip.DoSomethingToDisplayValidationErrorForElement(element, error); }
else
{ qtip.DoSomethingToHideValidationErrorForElement(element); }
}
};
$(someForm).validate(formValidationOptions);
this.SetupValidationRules();
};
this.SetupValidationRules = function() {
$(someFormElement1).rules("add", { required: true, minlength: 6, maxlength: 20, alphaNumeric: true });
$(someFormElement2).rules("add", { required: true, minlength: 6, maxlength: 20 });
$(someFormElement3).rules("add", { required: true, email: true, });
};
}
I currently am sure I can remove the need for the validation rules method by adding a custom binding so I can set the validation in the data-bind, however if possible I would like to use the same sort of callback approach with the existing Knockout-Validation binding.
I haven't used Knockout-Validation specifically but I have written something similar in the past. A quick glance at the source shows that each extended observable gets a sub-observable isValid. This could be used to hide show messages in your markup using conventional knockout visible bindings.
To get QTip to work a custom binding could subscribe to this isValid property and perform the necessary initialization to show/hide QTip when triggered.
EDIT
Here is an example to get you started
http://jsfiddle.net/madcapnmckay/hfcj7/
HTML:
<!-- Note that you have to reference the "qtipValMessage" binding -->
<!-- using the "value" binding alone is not enough -->
<input data-bind="value: emailAddress, qtipValMessage : emailAddress" />
JS:
ko.bindingHandlers.qtipValMessage = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var observable = valueAccessor(), $element = $(element);
if (observable.isValid) {
observable.isValid.subscribe(function(valid) {
if (!valid) {
$element.qtip({
overwrite: true,
content: {
text: observable.error
}
});
} else {
$element.qtip("destroy");
}
});
}
}
};
I had been editing madcapnmckay's post, but the differences have become significant enough that I think a new answer is needed.
It is heavily based off of madcapnmckay's post, but it fixes a bug pointed out by MorganTiley. The original only works if the user has modified the observable. If they haven't then the code never gets fired. So, I've modified it so that it fires the tooltip code when it gets created, in addition to when it changes.
ko.bindingHandlers.qtipValMessage = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var observable = valueAccessor(), $element = $(element);
if (observable.isValid) {
var updateTooltip = function (valid) {
if (!valid) {
$element.qtip({
overwrite: true,
content: {
text: observable.error
}
});
} else {
$element.qtip("destroy");
}
}
updateTooltip();
observable.isValid.subscribe(updateTooltip);
}
}
};
The one downside is that the tooltip will display on hover before knockout validation has been run (example, you have a "required" validation on a field, before you press submit a tooltip will display saying the field is required, but the field will not highlight in pink). Once you change the field however, the tooltip will disappear if the field is valid.
My app was not using qtip, but rather Twitter Bootstrap Tooltip, so here is the code for that as well.
ko.bindingHandlers.invalidTooltip = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var observable = valueAccessor(), $element = $(element);
if (observable.isValid) {
var updateTooltip = function (valid) {
if (!valid) {
$element.attr("data-original-title", observable.error);
$element.tooltip();
} else {
$element.tooltip("destroy");
}
}
updateTooltip();
observable.isValid.subscribe(updateTooltip);
}
}
};

Categories

Resources