knockout.js , Passing a constant or parameter to the data-bind click function in KO.js

Passing a constant or parameter to the data-bind click function in KO.js


Tag: knockout.js

I want to implement a menu. Each button in menu should set the menu ID in the model. I tried to do it this way, but it doesn't work:

<a class="btn btn-primary btn-large"

Instead the selectUi is called when the page loads.

The only possible solution which comes right now to my mind is to implement one function for each button. Is that the right way?


Wrap your function call in a function.

<a class="btn btn-primary btn-large"
     data-bind="click:function () { selectUi('menu'); },visible:sessionId()!=''">

You could also make selectUi return a function.


Notify that value changed in plain array

Currently I'm bound to plain array. Values of the array can be changed by external components. Is there any possibility to send notification that value has changed and re-render DOM tree? I can't use observables, thus valueHasMutated is not a solution, array is very large and contains lot of complex...

knockout js css biniding doesn't save changes

knockout js css biniding doesn't save changes after div's class was changed: My model contain 2 properties: man: '', woman: 'active' And I have 2 element in dom, which classes can be changed. <input type='button' value='Is MAN?' class='' data-bind='css: man'> <input type='button' value='Is WOMAN?' class='' data-bind='css: woman'> I want to...

How can I make Kendo UI Panelbar “skip” an element when reading an HTML list?

I'm using Knockout.js 3.3 and utilizing components with custom elements. I am trying to use Kendo UI's Panelbar with that list. The only problem is, it fails (the nested <ul> won't expand) because my lists are in the following format: <ul> <sidebar-step> <li>some message <ul> <li>some sub message<li> <li>another sub...

In a table which is data bound using knockout how to dynamically select any column values from view model

I've a view model which I am binding to the view- JSFiddle link to the code- In the view model, I've two arrays- grid, kpis I am binding 'kpis' in to drop downs options. 'grid' is an array which has 4 properties named as 'Promoters', 'Positive', 'Negative', 'Neutral'. 'kpis'...

Knokout select : Set Selected Item by item name not value

i have a knockout select as following observable Array issuingCountries 0: ObjectCoordinatorRegion: "EU" Country: "Australia" CountryId: 14 Id: 1 2: ObjectCoordinatorRegion: "AU" Country: "Japan" CountryId: 16 Id: 2 html <select class="issuing_country" data-bind="options: issuingCountries, optionsText : 'Country', value:IssuingcountrySelected, optionsCaption:'---Select---', " > </select> My question , i have { Country: "Japan" }...

knockout binding for datepicker with dynamic options

I am using knockout binding for jquerry date picker. refer the same code is working fine except i cant set datepicker options dynamically. How to set datepicker option(like mindate max date etc) dynamically(button click) using the the above reference link....

Automatically call a click handler to load a jQuery dialog box on page load

I've got a page, on the page there is a button wrapped in an anchor tag: <a href="javascript:void(0)" data-bind="click: AddNewThread, text: 'Add New Discussion'" class="btn new"></a> This calls a function labeled as AddNewThread, now this function opens up a dialog Box using jQuery, and in the dialog box there is...

Mapping a JSON object to a knockout array using mapping plugin

function PanelViewVM() { var self = this; self.PanelName = ko.observable("Test"); self.PanelDetails = ko.observableArray([]), self.SelectPanel = function () { $.ajax("/DPanel/FillIndex", { dataType: 'json', contentType: 'application/json', success: function (data) { ko.mapping.fromJS(data.PanelDetails, {}, self.PanelDetails); }, error: function (data) { console.log(data); } }); }; self.SelectPanel(); }; ko.applyBindings(new PanelViewVM()); JSON ajax response is: { "PanelDetails":...

Modular Web Components with View-Based Data-Binding context

I'm trying to make my code as modular as possible and mimic the patterns of WPF and Caliburn.Micro. Here's what I've tried so far using Knockout components. Component ViewModel function welcomeViewModel() { this.greeting = 'Hello world!; } App ViewModel function appViewModel() { this.firstGreetingVM = new welcomeViewModel(); this.secondGreetingVM = new welcomeViewModel();...

How to trigger ajax loading with an observable varariable in knockout?

I got some tabs in a page. When clicking on a tab, the currentTab changes its value, which should trigger an ajax loading of a new tab content. The concept is similar to a ko.computed, which however, only update another variable as the value change takes place. Is there any...

General function for observable array search

is there a way to do a general function for search an observable array and if the value found then set that object to another observable .? this question relate to Knokout select : Set Selected Item by item name not value so far i have tried self.getOptionByName = function(instance,opt,name){...

Modal from inside Bootstrap Tabs using Knockout foreach

I have Bootstrap tabs bound to a KnockoutJS observable array using a foreach binding, which is working fine. I now want to launch a Bootstrap modal from inside the active tab. <div class="tab-content"> <!-- ko foreach: trueData --> <div class="tab-pane fade in" data-bind="css:{active: $index() == 0}, attr :{'id': 'tab' +...

Knockout subscription insight: detecting if disposed

I have a subscription management in my ko model, which saves any subscription by intercepting them and saving reference to them. I then dispose() them, but I need to understand sometimes if a sub is already disposed. Is the member Gb, a boolean of the subscription object, an active-inactive flag?...

Dragstart event breaks the sequence

Below is my code: <body> <table border="1"> <tbody data-bind="foreach: $root.list1"> <tr data-bind="event:{dragstart: $root.dragStart, dragend: $root.dragEnd}" draggable="true"> <td data-bind="text: Id"> </td> <td data-bind="text: Name"> </td> </tr> </tbody> </table> <table border="1" data-bind="event:{drop: $root.dragDrop, dragover: $root.dragOver}"> <tbody data-bind="foreach: $root.list2"> <tr> <td data-bind="text: Id"> </td> <td...

knockout.js foreach $data AND $index()?

HTML You can see in the html I am calling editUser with two parameters. $data being the first parameter and $index() being the second. It should send the current user object in the first parameter and the index of the foreach loop as the second. <tbody data-bind="foreach: users"> <tr> <td>...

Css negation giving type error

In my model I have self.isAssetForTradingEnabled = false; and when I try to bind it to add some style like this: <tr data-bind="css: { 'selected': quantity() > 0 , 'disabled': !isAssetForTradingEnabled() }"> Then Knockout gives a type error. It works if I change isAssetForTradingEnabled = true; and 'disabled': isAssetForTradingEnabled ...

Knockout text binding showing the value

I am trying to text bind one element to a paragraph tag. It's not working properly and not giving any error in Browser. I am using Visual Studio for development. I created a fiddle for showing the problem and there i got the error that my binding is not defined....

How to use current object in a computed observable? — Knockout.js

I have a foreach data-binding on an array. I want to access the current object or place in the computed observable (as it happens with the click data-binding). Example: Here is my View: <tbody data-bind='foreach: items'> <tr data-bind="attr: {class:$root.changeClass()}"> <td data-bind='text: name'></td> </tr> </tbody> And, here is the view-model: function...

Bindings doesn't work on nested template loaded by JSON in KnockoutJS

Yesterday I make this question: How can I refresh or load JSON to my viewModel on Knockout JS with complex models Everything works OK with the fixes but when I try to use a complex json to load in the viewModel some of the buttons (specifically on Groups) doesn't work....

Is it possible to inherit ko.computed to a prototype class?

Let's say that I wish to have the behaviour a ko.computed has with: read write but I want to have an internal observable inside that ko.computed property, something like: this.a = ko.computed(function() { value: ko.observable(null), read: function() { return value; }, write: function(newValue) { if (newValue) { value(newValue); } }...

How to declare knockout component in typescript?

I am trying to follow example to create a component in knockout. But I have to write a code in typescript. So how can I register component in knockout using typescript? What should I write in .ts file to convert it in something-like below. ko.components.register('like-widget', { viewModel: function(params) {...

Knockout enable binding

Tried different methods to disable some textbox's on a binding: Here is a fiddle: What I am trying to do is when the user presses the + button is to disable all the textbox's on the previous row so they are not editable. I have tried intercepting the knockout...

KnockoutJS cannot perform value binding with select

My ViewModel is like this: $(document).ready(function () { vm = new poReceivingModel(); ko.applyBindings(vm); }); function poReceivingModel(){ var self = this; self.order_id = ko.observable() } And my html is like this: <select id="id_po" class="form-control" name="po" data-bind="value:order_id"> <option value="1">4323</option> <option value="2">1234</option> </select> <h1 data-bind="value: order_id">It is</h1> When I select option of the...

Loop viewmodel display pattern images on select change

I am loading 3 selects with the following model: var viewModel = function(){ var self = this; self.makes = [ {id: 1, name: 'Northwoods Prestige'}, {id:2, name: 'Forest Bay'}, {id:3, name: 'Timberland'} ]; self.types = [ {id: 1, make:1, name:'Special Reserve 138', patterns:['11.jpg','12.jpg']}, {id: 2, make:1, name:'Special Reserve II', patterns:['13.jpg','14.jpg']},...

Updating ViewModel knockout with a nested loop

This may not be the completely ideal optimized way of accomplishing the task. I'm open for suggestions on any better ways. So far the loads work fine performancewise. I have my knockout app working via ajax load. Inside the binding calls, I have a nested loop that includes a function...

Why doesn't CSS transition get applied?

I've built a small stacked bar visual just using floated divs that underneath is bound to some data using knockout. What I want to be able to do is to animate changes in the size of these stacks when the data changes. I've managed to do this in the general...

KnockoutJS custom binding cannot trigger update callback on observable change

When my observable array is changed, the update callback is not triggered. Please help. Here is my custom binding: ko.bindingHandlers.selectizeBinding ={ update: function(element, valueAccessor){ var value = valueAccessor(); var ords = ko.unwrap(value); alert(ords); }, init: function(){}, } My ViewModel is like this: function poReceivingModel(){ var self = this; self.order_id =...

Horizontal image list modules to be used wit KO.js and Bootstrap

I'm evaluating how to implement a UI with Knockout.js and Bootstrap. Basically, what I want to achieve is a horizontal list of images, (ideally scrollable) where each image also has an information frame. The list is populated from KO-observableArray. <div data-bind="foreach: thumbnails"> <span> <a href='#' data-bind='click: select '> <img width="120"...

What is difference between Init and update function of knockout js custom binding

i like to know what is difference between Init and update function of knockout js custom binding ? when we should write code inside init function and when we should go for update function of knockout js custom binding. i go through knockout js doc but still my understanding for...

Why is KnockoutJS not showing the same number of objects as my Web API controller?

The solution was the same as in this question: How to get an observableArray's length? ...but the question itself is unique so anyone in the same situation will hopefully have an easier time finding the answer than I did. I'm fairly new to Knockout and to Web API. I've built...

How to implement custom sort for koGrid?

Data: 16.00 hours 19.99 hours 210.46 hours 262.54 hours 303.19 hours 55.95 hours 60.07 hours 64.07 hours 7.95 hours What I want: I need to allow sorting for this king of data in koGrid (default feature by clicking grid header, asc or desc sort). Problem: The data is string so...

WHY does it initialize this Knockout.js component in random order?

I am beyond confused... I am creating a list using Knockout.js components, templates, and custom elements. For some reason, the steps I create in my Viewmodel are being initialized in random order within the custom element definition! And it is completely randomized so that it is different each time! To...

Passing $index and $data as arguments to function for click handler

I am passing $index and $data to the change_model function. The function is expecting 2 parameters in the following order: (index, data). From the viewModel I am passing click: $root.change_model.bind($data, $index()). Within the function index prints $data, and data prints index: values are reversed. self.change_model = function(index, data) { self.patternSelectedIndex(index);...

knockoutjs make selectable items onclick within foreach

I am looping items within a foreach statement. On page load, by default I am selecting the first item (data-bind="css: { selected: $index() == 0 }"): var viewModel = function(){ var self = this; self.pattern_index = 0; = function(data) { //handle click }; self.makes = [ {id:1, name: 'Northwoods...

Observe MyArray().length knock out

Is it possible to store length on an observable array in an observable variable and bind this to the view, something like this? self.MyArray = ko.observableArray([]); self.MyArraylength = self.MyArray().length; //Bind in view self.Observelength = ko.observable(self.MyArraylength); When I alert MyArray length it seems to update proper, but cant get it to...

Binding html to ko-observables.

In this example <strong>Test:</strong> <span data-bind="text: currentResult()? currentResult().test_name : '' " /><br/> <strong>SampleId:</strong> <span data-bind="text: currentResult()? currentResult().sample_id : '' " /><br/> I see only one text - only the first: Test: <test_name> If I exchange the lines, I see only SampleId:<my sample id> It is not because of height limits....

How can I add HTML to this Knockout.js Viewmodel variable? [duplicate]

This question already has an answer here: HTML Entities with Knockout 1 answer I have a list of steps displayed on the page. Some steps (but not all) will have 1-3 substeps. I was thinking the simplest way of doing this was to just write the HTML manually within...

Knockout JS Validation not working

I am a newbie in Knockout JS. i want to apply validations in KO. i have used plugin knockout.validation.min.js . I have implemented it like this but not working My View Model $(document).ready(function myfunction() { ko.applyBindings(new EmployeeKoViewModel()); }) var EmployeeKoViewModel = function () { var self = this; self.EmpId =...

Update Knockout Observable string in refresh function

The code is in typescript and I am trying to show current date time on page load and update that date time on refresh click. In .ts file string that shows date time is declared like this. asOfString: KnockoutObservable<string>; In the constructor it is being set like this, this.asOfString =...

How to get the component's viewmodel from component's node in KnockoutJS

I have a component named 'my-component': ko.components.register('my-component', { viewModel: function() { return { title: 'title' }; }, template: '<div>x</div>' }); I'm using this component in the view like that: <my-component params=""></my-component> Is there any way to get the component's view-model related to this HTML node? ko.dataFor doesn't work: ko.dataFor($('my-component').get(0)) //...

Checkbox to be checked on having value Y,knockout.js
I have a checkbox bound to a viewmodel's observable property, whose value will be Y or N. I want the the checkbox to be checked when the value is Y and unchecked when the value is N. How to achieve this? I am able to achieve it if the value...

button click to set an optionsCaption value as default in knockout

I am currently working on options binding in knockout, the bindings is doing everything for me as per my requirement. But currently the problem I am facing is how to set optionsCaption Value again to my Select Box on a button click. Here is my code var clickMe = function(){...

Knockout js unable to bind data using observableArray

I am trying to display all the employees in the database and I am unable to achieve it. My JS, var EmployeeKoViewModel = function () { var self = this; self.EmpId = ko.observable(""); self.Name = ko.observable(""); self.City = ko.observable(""); self.Employees = ko.observableArray([]); GetEmployees(); function GetEmployees() { $.ajax({ type: "GET", url:...

knockout.js with kendo UI MultiSelect over MVC 5

Currently I have the following code, MVC with knockout bindings (this works fine) @Html.DropDownListFor(m => m.profiles, (SelectList)Model.profileItems, new { id = "ID", data_bind = "options: Profiles_msl, optionsText: 'profiles', optionsValue: 'ID'" }) I also have this which is kendo UI with MVC model bindings (no knockout). This also works. @(Html.Kendo().MultiSelect() .Name("Profiles")...

Avoid error of cyclic value in view, knockout

My knockout model (version 3.3.0 of knockout) is something like this: var Node= function(id,name,parentNode) { var self = this; ko.observable(id); //more here... self.nodes = ko.observableArray([]); self.parentNode = parentNode; } When this model is bound to a view, knockout throws an error in the console (non-breaking error): TypeError: cyclic object...

Passing a constant or parameter to the data-bind click function in KO.js

I want to implement a menu. Each button in menu should set the menu ID in the model. I tried to do it this way, but it doesn't work: <a class="btn btn-primary btn-large" data-bind="click:selectUi('menu'),visible:sessionId()!=''"> Menu </a> Instead the selectUi is called when the page loads. The only possible solution which...

Check box in table header to check all checkboxes in other rows

I have a checkbox in my table header to select/unselect all checkboxes in the table.I tried to bind change/click event to that. same event is working for other check boxes but not for the check box on header. I am using MVC3 & KnockoutJS bindings. Added code part below. <tr...

How to trigger a function with textInput binding?

I'm using Knockout.js 3.3.0. In my viewmodel I have a lot of data rows that I present in a table with a foreach binding. In every row there is a text input that is bound to an observable. What I want to achieve is this: whenever the text changes, it...

Validation message not appearing

On adding ko validation extender to dynamic objects it is not displaying the error message when showAllMessages() is called. There is also no span tag added below the respective controls which will show the error message. I also like to show the error message just below the control as soon...

KnockoutJS custom component loader not executing `loadViewModel`

Context I have been fiddling around and trying to create my own (just another) SPA framework. In this framework I've been trying to create a custom component loader to be able to do some dependency injection 'n stuff on the viewModels I'm loading. Used KnockoutJS version: 3.3.0 Problem The loadViewModel...