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


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

Question:

Tag: knockout.js

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 knockout js custom binding is not very clear to me.

i just wonder if someone help me to understand when we go for init and when we go for update with example.

here i am point out some code which not very clear and their intention.

Code for Init function

<div data-bind="allowBindings: true">
    <!-- This will display Replacement, because bindings are applied -->
    <div data-bind="text: 'Replacement'">Original</div>
</div>

<div data-bind="allowBindings: false">
    <!-- This will display Original, because bindings are not applied -->
    <div data-bind="text: 'Replacement'">Original</div>
</div>

ko.bindingHandlers.allowBindings = {
    init: function(elem, valueAccessor) {
        // Let bindings proceed as normal *only if* my value is false
        var shouldAllowBindings = ko.unwrap(valueAccessor());
        return { controlsDescendantBindings: !shouldAllowBindings };
    }
}; 

Code for Update function

<input type="text" data-bind="value: someText, customBinding: someText">

ko.bindingHandlers.customBinding = {
    update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var value = ko.utils.unwrapObservable(valueAccessor());
       console.log( JSON.stringify(value) );       
    }
}

ko.applyBindings({
    someText: ko.observable("inital value")
});

Answer:

Knockout documentation clearly states where these these methods are used:

Knockout will call your init function once for each DOM element that you use the binding on. There are two main uses for init:

Knockout will call the update callback initially when the binding is applied to an element and track any dependencies (observables/computeds) that you access. When any of these dependencies change, the update callback will be called once again.

Short answer is init function is called once when the binding is initialized, and update function is called every time when there is an update in the value bound. You can find examples in the link above, I don't think it is worth copying them here.


Related:


Modal from inside Bootstrap Tabs using Knockout foreach


jquery,twitter-bootstrap,knockout.js,twitter-bootstrap-3
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' +...

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


ajax,knockout.js
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...

How to trigger a function with textInput binding?


javascript,knockout.js
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...

knockout binding for datepicker with dynamic options


knockout.js,jquery-ui-datepicker
I am using knockout binding for jquerry date picker. refer http://stackoverflow.com/questions/6612705/jquery-ui-datepicker-change-event-not-caught-by-knockoutjs 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....

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


javascript,jquery,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...

Notify that value changed in plain array


javascript,knockout.js
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...

Knokout select : Set Selected Item by item name not value


jquery,select,knockout.js
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" }...

How to implement custom sort for koGrid?


javascript,sorting,knockout.js,typescript,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...

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


javascript,json,mvvm,knockout.js
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....

Avoid error of cyclic value in view, knockout


javascript,json,knockout.js
My knockout model (version 3.3.0 of knockout) is something like this: var Node= function(id,name,parentNode) { var self = this; self.id= 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...

knockout.js with kendo UI MultiSelect over MVC 5


javascript,knockout.js,asp.net-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")...

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


jquery,knockout.js
I've a view model which I am binding to the view- JSFiddle link to the code- http://jsfiddle.net/piyush4bpl/9kq2t5xu/ 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'...

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


javascript,jquery,knockout.js
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...

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


html,knockout.js,kendo-ui,kendo-panelbar
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...

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


knockout.js,asp.net-mvc-5,web-api
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 declare knockout component in typescript?


javascript,knockout.js,typescript
I am trying to follow example to create a component in knockout. http://knockoutjs.com/documentation/component-overview.html 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) {...

Why doesn't CSS transition get applied?


javascript,html,css,knockout.js
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


javascript,knockout.js
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 =...

Updating ViewModel knockout with a nested loop


javascript,jquery,knockout.js
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...

Modular Web Components with View-Based Data-Binding context


javascript,html,knockout.js,data-binding
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();...

button click to set an optionsCaption value as default in knockout


knockout.js
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(){...

Checkbox to be checked on having value Y


asp.net-mvc,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...

knockoutjs make selectable items onclick within foreach


knockout.js,knockout-3.0
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; self.select = function(data) { //handle click }; self.makes = [ {id:1, name: 'Northwoods...

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


javascript,html,knockout.js,knockout-components,knockout-templating
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...

General function for observable array search


knockout.js
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){...

Knockout JS Validation not working


javascript,asp.net-mvc,knockout.js
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 =...

Knockout enable binding


knockout.js
Tried different methods to disable some textbox's on a binding: Here is a fiddle: http://jsfiddle.net/tonymaloney1971/jpswf04L/ 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...

Observe MyArray().length knock out


javascript,knockout.js
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.


knockout.js
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....

KnockoutJS custom component loader not executing `loadViewModel`


javascript,knockout.js,requirejs,knockout-components
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...

Update Knockout Observable string in refresh function


javascript,knockout.js,typescript
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 =...

Dragstart event breaks the sequence


javascript,knockout.js
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...

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


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" data-bind="click:selectUi('menu'),visible:sessionId()!=''"> Menu </a> Instead the selectUi is called when the page loads. The only possible solution which...

Loop viewmodel display pattern images on select change


javascript,knockout.js,knockout-mvc,knockout-3.0
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']},...

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


javascript,knockout.js
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)) //...

Knockout subscription insight: detecting if disposed


knockout.js,subscriptions,singlepage
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?...

Mapping a JSON object to a knockout array using mapping plugin


javascript,jquery,knockout.js
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":...

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


javascript,knockout.js,observable
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); } }...

Validation message not appearing


javascript,knockout.js,knockout-validation
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 cannot perform value binding with select


javascript,knockout.js
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...

Knockout js unable to bind data using observableArray


knockout.js,asp.net-mvc-5
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:...

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


jquery,knockout.js
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...

knockout js css biniding doesn't save changes


javascript,knockout.js
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...

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


javascript,knockout.js
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>...

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


javascript,knockout.js,knockout-3.0
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);...

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


javascript,html,knockout.js,knockout-components,knockout-templating
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...

Css negation giving type error


knockout.js,knockout-2.0
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 ...

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


knockout.js
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...

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


jquery,twitter-bootstrap,knockout.js
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"...

Knockout text binding showing the value


javascript,jquery,knockout.js
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....