Knockout.js Knockout afterRender, but just once

I have a simple observableArray which contains a lot of user-models. In the markup, there is a template with a foreach loop which loops the users and outputs them in a simple table. I additionally style the table with a custom scrollbar and some other javascript. So now I have to know when the foreach loop is finished and all the models are added to the DOM. The problem with the afterRender callback is that it gets called every time something is added, but I need kind of a callback which fires

Knockout.js Knockout - Event seems to fire on page load?

I have a ViewModel which has a dropdown like so: <select data-bind="options: orderDropdown, value: selectedOrder, optionsCaption: '---', event: { change: loadOrderDetails }"> </select> Then the loadOrderDetails is set like this: // loads details of selected order self.loadOrderDetails = function () { $.ajax({ url: "/api/OrderDetails", data: { id: self.selectedOrder() }, type: "GET", success: function (data) { self.order

Master detail views with Knockout.js - how to update master?

I'm working on a master detail view using Knockout.js. Basically, everything works fine, with one little drawback: Whenever the item that is currently shown in the detail view is changed, the master does not update itself accordingly. Basically, I understand why this is: The master view is based upon a ko.observableArray and as such it only keeps track of inserting and removing items. It does not react on updated items. Whenever an item is selected, it is put into a ko.observable which is the

Knockout.js Knockout not detecting change

I have a page with a knockout.js model. I am 'serializing' the data to a textbox in JSON format by binding a computed property of the serialized object. Selection of the parts that work: View Model function CourseParticipant(name, facility) { var self = this; = ko.observable(name); self.facility = ko.observable(facility); } function CourseParticipantViewModel() { var self = this; self.participants = ko.observableArray(); self.participants.push(new CoursePa

knockout.js search observable array for text freezes

I have an issue where I am searching on keyupdate on an observable array and sometimes the page freezes. It happens when "indexOf" is inserted in the logic. I just want to hide the objects that are filtered out. It mainly happens when I go under 2 characters. There are 1500 rows. Another thing I noticed this only happens in Chrome, but in IE it works just fine quick! JS var self = this, intervalId = null; self.powerSchoolCourses = ko.observableArra

Knockout.js Knockoutjs Array Filter

Can someone please help me with this? How do I get the multi select list to have unique countries? Also, how do I filter the records based on the items selected in the multi select? Here's the code in JsFiddle Please help. Thanks. HTML <div class='liveExample'> <p style="color:red">How do I make this list unique?</p> <p> <select data-bind="options: people,optionsText: 'country', selectedOptions: selectedCountries" size="

Knockout.js Kendo-Knockout - how to bind AutoComplete to remote data?

I using Kendo-Knockout. I am trying to get the AutoComplete to bind to remote data. Using the basic example at I've tried the following. However, search is not updated until the input has lost focus. "search" only looks for something if it is already in the observableArray. The only event provided with the Kendo Autocomplete is "change", which again only fires after the input has lost focus. How would you intercept the key pre

Knockout.js Custom binding valueAccessor has unexpected result

I am stumped by the following behavior in a custom binding of knockout.js: ko.bindingHandlers.customBinding = { update: function(element, valueAccessor, allBindingsAccessor) { var value = ko.utils.unwrapObservable(valueAccessor()); console.log( JSON.stringify(value) ); } } ko.applyBindings({ someText: ko.observable("inital value") }); and <input type="text" data-bind="value: someText, customBinding: {some: 'option'}"> The valueAccessor() should give me t

Knockout.js Breeze requires knockout when use requirejs

I'm getting some odd behaviors loading breezejs in an application that also uses requirejs. The main issue is that if I setup require to load breeze (plus its dependencies q and jquery), breeze fails to load unless knockout is setup as a dependency of breeze. Uncaught Error: Module name "ko" has not been loaded yet for context: _. Use require([]) That's fine if I actually wanted to use knockout, but I'm using angular. I guess it doesn't break anything to load knockout too, but it's a

Knockout.js How to put a computed observable as a cell data in Handsontable

I have already integration of Handsontable with KnockoutJS here ko.bindingHandlers.handsontable = { init: function (element, valueAccessor, allBindingsAccessor) { var value = valueAccessor(); // TODO: what happens if value is null? var allBindings = allBindingsAccessor(); var colHeaders = allBindings.colHeaders() || true; var data = allBindings.handsontable(); // TODO: make options cust

Knockout.js nested model and observable arrays

I'm new to Knockout and have some problems at the beginning. Consider following model: // @param {String} content Content of the post // @param {number} reply_to ID indicating to which post this post is replying // @param {Array} replies Array of DiscussionPosts indicating replies to this post var DiscussionPost(content, reply_to, replies) { var self = this; self.content = content; self.reply_to = reply_to; self.replies = ko.observableArray( ko.utils.arrayMap(replies, f

Knockout.js see all extenders and custom bindings for observable

Is it possible to see all extenders and bindings attached to an observable within Knockout JS? Sample View Model: var viewModel = function(){ var self = this; self.firstName = ko.observable().extend({required: "Please enter a name", logChange: "first name" }); self.lastName = ko.observable().extend({ required:true}); } I am also using several custom bindingHandlers including the Knockout X-Editable Plugin in addition to the KO Validation Pl

Knockout.js Knockout Can't Access ObservableArray from inside model

This might be pretty basic but I just can not seem to figure it out. The problem goes I have a view model with an observable array 'self.product' and want to access it from a nested model as shown below. when I run this I get an error that product does not exist. I have not included the code but there is an ajax call that gets data and pushes it to 'product'. Also using a click binding on the function 'test' does print the value. I though it might be a scoping issue with the 'self' but since I

Knockout.js Using Durandal Composition manually

I have an empty container in my html like: <div id='workspace-container'></div> I want to create my model manually and compose it with some view, then inject the result into the #workspace-container using javascript like: var myViewModel = new ViewModel (param1, param2); // Doing some actions on myViewModel // Some MAGIC here: composition.compose(myViewModel, myView, '#workspace-container'); What is the api to do such magic!? Update1: In fact I need manual binding for a reaso

Knockout.js Set default focus when 'If' binding expression turns true

I have a form with the 'If' binding applied and some input controls in it. So it looks similar to this: <form data-bind="if: MyExpression"> <input id="input1" class="autofocus"></input> <input id="input2"></input> <input id="input3"></input> </form> Now, I want to set focus on the input with the 'autofocus' class whenever 'MyExpression' turns true and the form shows up on screen. Any Ideas how to achieve that? I tried this so far: thi

why is setting observable in knockout.js not working

I'm trying to explicitly set a default value on some observables, but after setting them and checking their values they return undefined. What am I doing wrong? Interestingly the selectedCustomerType is set as expected, however the other 2 variables, selectedPlatform and selectedPricing are null. What is my silly mistake? HTML: <!doctype html> <html> <head> <meta charset='utf-8'> <script src='static/javascript/jquery-1.9.1.js'></script> <script src

Knockout.js How to make input visible only when dropdown selection equals value using KnockoutJS

I'm new to KnockoutJS and having trouble getting the text and input "Other Reason" to only be visible when in the dropdown "Other" is selected. Please help. <div id="reasonPopup" class="selectItems" style="display: none; position: absolute; width: 200px; height: 150px;"> Choose an Reason:<br /> <select data-bind="options: reasons, optionsText: 'reasonText', optionsValue: 'reasonValue', value: chosenReason, optionsCaption: 'Choose...'"></select> <p data-bind="with: c

Knockout.js Tooltipster not applied to Knockout dynamic elements

I'm trying to get tooltipster tooltips on some dynamic content generated from knockout. It's a simple list that has a name and edit/delete buttons (which I want the tooltip on). It's populated via a call to but I've recreated a simplified version of it. Here's the HTML: <body> <button class="tooltip" title="This one works">Static... it works</button> <ul data-bind="foreach: fields"> <li> <div data-bind="text: name"></div>

Knockout.js KnockoutJS: Enable/disable a checkbox when value of a text (number) input is > 0

I'd like to ask a user how many children he/she has, and when he/she has more than 0, a checkbox "single parent?" should be enabled, otherwise disabled. I'm very new to KnockoutJS and made my through the tutorials on the page, but I seem to fail at this very basic need. I made a jsfiddle here: One important thing: when an existing user edits his info, the number of children is read from the database, so the <input value="xxx" /> should be respected by

Split viewmodel into multiple viewmodels in knockout.js

In Knockout.js, when your ViewModel gets quite big, there are different ways to split into multiple ViewModels and it is always a good idea to have a number of smaller ViewModels instead of having one big one. I am using the following approach and not sure if there is any other better way of doing this. Note I am using require.js to define my ViewModels but I am not including that code in the example below for the sake of simplicity. In the following example let's say that I am working on a scre

Knockout.js Component lifecycle

Below is an example that creates a simple component. According to it's possible to add a dispose function that get's invoked by ko when the component is removed from the DOM. I'm looking for something similar that would allow me to hook into step 5 The component is active. additional info as requested by comment In the example below I'd like to a) insert the DOM fragment created by the ko component and b) once it's

Knockout.js KnockoutJS click binding does not work as expected

I have the following code (shell is global to my application and is not in my viewmodel): <div data-bind="if: shell.metadata().User().IsRootUser()" class="up-one-level text-center"> <a data-bind="click: shell.navigateToLandingPage" class="btn btn-admin">@Global.BackToAdmin</a> </div> Access to shell.metadata() works fine in the if data-bind, but in the click data-bind, I got a null value for shell. I also tried some variants like <div data-bind="if: she

Knockout.js Between two numbers validation in knockout?

I am trying to write a validation which performs like similar to between . I am having a textbox and i want show error message if he failed to enter anything other than the given range . ViewModel : var vm = function viewModel() { var self = this; self.mainamount=ko.observable(); self.amount1=ko.observable(2); // this will be dynamic self.amount2=ko.observable(100) self.validation = ko.validatedObservable({ self.mainamount.extend({required:true,number:true,min:self.amount1,max:self.amount2})

Knockout.js KnockoutJS: setting checked value to something other than true or false

When I use 'value' with a select, I can store a reference to an model as the value. <select data-bind="value: selectedOption, attr: {name: $}, options: options, </select> The above works very well. The model is stored in a parent model, so I can access all of it's properties elsewhere. With a checked, I can only store true and false: <input type="checkbox" data-bind="checked: $parent.selectedOption, checkedValue: $data" /> In this case, $parent.selectedOpti

Knockout.js Showing a concatenated string from multiple values of observable array

I have an observable array as follows.. var myObservableArray = ko.observableArray([ { name: "Bungle", type: "Unknown" }, { name: "George", type: "Unknown" }, { name: "Zippy", type: "Unknown" } ]); I wish to fill a select listbox from elements in the observable array such that the option names are concatenated string of 'name' and 'type' like "Bungle-Unknown","George-Unknown",.etc The optionvalues are just 'name'. Any help is sincerely appreciated. Thanks

Knockout.js Bootstrap dropdown binding using knockoutjs

I'm new to knockoutjs so I really need some advice how to accomplish this requirement. In my jsfiddle, I have link with dynamic displaying of data in modal. I'm using this to populate the data in dropdown var eventViewModel = function() { var me = this, eventTypes = [{ cls: 'fa fa-fw fa-globe', label: 'Create Public Venue', text: 'Visible to anyone', url: "Link-to-Public" }, { cls: 'fa fa-fw fa-lock', label: 'Create Private Venue', text: 'Visi

Knockout.js knockout - array of objects and view, right way?

I have an array of objects in which each object represents data for a view view. I want to initiate a set of properties for each of the objects so that I can easily add onto the objects from one function. The way I am doing this is like so. var createViewProperties = function () { return { rightContentVisibility: ko.observable(true) // normally false, true for testing }; }; var data= [ { headline: "Are you interested in helping others?", viewPropert

Knockout.js ul li index() once recognized once not

I have following code which works just fine <form class="form-horizontal"> <ul data-bind="foreach: SelectedCategories"> <li> <input type="hidden" data-bind="attr: { Name: 'SelectedCategories[' + $index() +']'}, value: $data" /> <span data-bind="text: $data"></span> <input type="button" data-toggle="tooltip" title="USUN" data-bind="value: 'X'

Knockout.js knockout binding object, field value will not update after input value

why binding on object ,the object value will not update. but the valueitem will change after keyup. function Model() { this.Id = "", this.Name = "aa" }; var vm = { item: ko.observable(new Model()), valueitem:ko.observable('bbbbb') }; ko.applyBindings(vm); <script src=""></script> <script src=""></script>

Knockout.js Is it possible the knockout ignores 'data-bind=with..." ?

Please take a look at the following code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <form data-bind="with: selectedMerchant"> <h1 data-bind="text: name"></h1> <button data-bind="click: show"> SHOW </button> </form> <script src="" type="text/javascrip

Knockout.js Aggregate multiple max KO extend validations

I am using ko extend validation to validate, Trying to do something like follows. ko.extend does not support multiple bindings for same type (max in this case) and it only adds first rule. Is there a way to conditionally pass the params with a function? or my only way out is writing a custom validation? myModel.prop2.extend({ max: { onlyIf: function () { var test = myModel.prop1() != undefined && myModel.

Knockout.js How to make the visible binding to work

I'm experimenting with Knockout.js, and can't make the visible binding to work in the following code when returning an empty array (here's its fiddle): $(document).ready() { BuildFactoryGrid(); } function BuildFactoryGrid () { var factoryViewModel = new FactoryViewModel(); ko.applyBindings(factoryViewModel); factoryViewModel.init(); } function FactoryViewModel () { var self = this; self.FactoryRecords = ko.observableArray([]); self.FactoryRecordsLength = ko.compu

Knockout.js Knockout - write different observed values for input and for style

An observable integer, that stores a value which is used for css variables, like width, or height. In order to be correctly applied in css, these variables need an additional unit, like px or mm. However, in my viewmodel I want to store pure integers and want to be able to change it in a input field. What I need now, is a way to tell knockout that whenever this value is inserted into a style- binding, it has to be augmented with the respective unit string (px).

Knockout.js CodeMirror custom binding doesn't work inside "foreach" binding

I have created a custom binding for CodeMirror. Custom binding works with a simple string, but inside foreach binding, it ceases to be initialized, although all the HTML and CSS is added. Here's a working snippet: var viewModel = { options: { mode: "text/x-csharp", lineNumbers: true }, //IT WORKS fileContent: "public sealed class DictionaryAttribute : Attribute{}1", //IT DOESN'T WORK codes: ["public sealed class DictionaryAttribute : Attribute{}1"] }; ko.bindingHandler

Knockout.js I need a clean way to access parent scope in knockout foreach

I have a lot of places where I use knockout data bound foreach loops. A good example would be a list of items, with a click button on the right side that says "edit". I find myself writing code that looks like the following: <div data-bind="foreach: myListData"> ... other divs ... <button data-bind="click: $parent.editItem.bind($data)">View</button> </div> The editItem function would then look something like the following: editItem: function (review, data)

Knockout.js Changes in 1 object property of observableArray changes same property of another object in same observableArray

If a property in one object is changed, the same property in another object gets updated in the same observableArray. From UI: If I click Change Address button on every accordion, it's calling populateSelectedAppoinment function and in this I can get current updated data in currentData. When I am assigning the values from currentData which are observables, to the first object of observableArray, while iterating over the same observableArray, same properties in a second object get modified with

Knockout.js Knockout Binding issue, can only get values with anonymous functions

I have an observable CommitteeTypes which holds an array of objects: self.CommitteeTypes = ko.observableArray(); self.init = function() { self.CommitteeTypes([ { Meeting: {descr: 'Committee', meeting_type_id: 'C' }, Ranks: [{}, {}, ...], Roles: [{}, {}, ...] } ]); } And then I have a Select dropdown: <select data-bind="options: $root.CommitteeTypes, optionsText: function(item) { return item.Meeting.descr; }, optionsValue: Meetin

Knockout.js How do I create a specified number of links in Knockout js

I would like to create a number of links (or any html element for that matter) based on a number that I have in my viewmodel. I want to do the equivalent of this in knockout js Psuedo code: for(var i; i < someNo; i++){ CreateHtmlElement(); } I've used the foreach binding with Knockout js before, and that lets me me create elements based on objects in an array, but I can't find anything that would do the same but for a count. Is this possible? Thanks in advance.

Knockout.js Knockout JS - Checkbox databind

I'm creating a checkbox that is bind to a property, like this: <input type="checkbox" data-bind="checked: hasSurname, enable: verified()"/> And this works fine. My problem is that i also want that to uncheck the checkbox when the user is not verified, so i do the next: <input type="checkbox" data-bind="checked: hasSurname && verified(), enable: verified()"/> This option has the correct behavior, but the hasSurname property never changes remaining false. Any help ple

Knockout.js Knockout - Viewmodel transformation

From the client side i have to make multiple ajax calls to a REST service that would give me three different domain models in JSON. Now at the client side i have to transform them into a viewmodel before binding them to the controls. Which would mean transforming them into a completely different structure with presentation only data. Any ideas or suggestions would be helpful.

Knockout.js BreezeJS + Knockout Not able to set input field to Null

Where a model uses nullable values such as public Nullable<int> Price { get; set; } When adding new records all is fine, Price is Not a required field so will be saved as Null value in the database. If I modify an existing record, let’s say I want to change the value of price from 10 to blank. Then I get a validation error. Validation error: ‘Price‘ must be an integer between the values of -2147483648 and 2147483647 However this field is not required so I would have expected it to ju

Knockout.js how to update the values of the edited row using knockout datatables extension?

Im loading more than a 1000 rows in a datatables using the knockout mapping these items into an observable array using map.fromjs and it realy slows down the initial loading of the page. to avoid this slow initial load up I tried to set the observable array to be filled with just plain json objects meaning the 1000+ objects contained in the array are not observable. but since the objects are not observable then when editions were done on the plain objects the changes weren't bein

Knockout.js Knockout subscribe to observable in js object within an observable array

I have a CoffeeScript class WorkOrderLabor ( that has an observable work_item_id. I would like to subscribe to this observable change and run some code. This is what I am doing: self.addWorkOrderLabor = -> wol = new WorkOrderLabor() wol.work_item_id.subscribe = (val) -> console.log val self.work_order.work_order_labors.push(wol) This doesn't work. It actually spits out the val when the function is called but not

Knockout.js How to reset knockout bindings in Jasmine test

I'm trying to write test for knockout feature with jasmine as below and I'm getting following error: Error: You cannot apply bindings multiple times to the same element. describe("ThreeStepNavigationView", ()=> { var testSubject; var SmallNavigationStates = ['ribbon','expanded']; var ExtraSmallNavigationStates = ['collapsed','ribbon','expanded']; beforeEach(()=> { loadFixtures('SidebarAndSiteHeader.html'); testSubject = new Mobile.Navigation.ThreeStepNavig

Knockout.js using knockout sortable with bootstrap popover

To use bootstrap popover, I'm using knockout-bootstrap but am ok with using something else as in the answer of Adam Marshall here Normally , on a button click event, I would use it as below.. <button class="btn" data-bind="popover: {template: 'popoverBindingTemplate', title: 'Popover', trigger: 'click'}"> I wish to trigger the popover on students in tables in the knockout sortable example. jsfiddle: I can not use it on click event as it throws an error : Multiple bindings (text and po

Knockout.js Knockout dynamic view with coordinations

I have a list of rectangles, each rectangle has coordination (x, y) and size (width, length). I need to build from this list a dynamic view that shows this rectangles at their size and place (of course this list can be change, so it's not hard-coded). Each rectangle has to be an HTML element (like DIV) because I need to insert text/images inside. For example - I did it two years ago with canvas, but I want to know - is there a way to create this view with KnockoutJS?

Data-Binding not working in knockout.js using datatable pagination

I am binding the list into table using Knockout.js. In this for sorting, pagination I am using the datatable. On 1st page data-binding is working correctly. But if I move to 2nd page it's not working. It will be great if somebody will help. I am new to Knockout.js.Here is my code <table id="datatable" class="table table-bordered thumbnail-table "> <thead> <tr> <th width="8%"> Pip Code</th> <th width="30%">Full Description &

  1    2   3   4   5   6  ... 下一页 最后一页 共 23 页