Observable array push multiple Objects in knockout.js

We do have ko.utils.arrayPushAll(array, valuesToPush) as a utility function that you can use. It is not available directly off of observableArrays though. If you add your pushAll to observableArrays, you would want to operate on the underlying array (this() in your case) and then call valueHasMutated() on the observableArray at the end. This will ensure … Read more

Adding properties to the view model created by using the Knockout JS mapping plugin

You need to use a create method on the mapping object itself like: var mapping = { //customize at the root level. create: function(options) { //first map the vm like normal var vm = ko.mapping.fromJS(options.data); //now manipulate the returned vm in any way that you like vm.someProperty = “test”; vm.someComputed = ko.computed(function() { return vm.first() … Read more

Unobtrusive Knockout

Great question. I’ve been writing complex KnockoutJS views for awhile and was never satisfied until I switched to Ryan Niemeyer’s class binding provider. The Knockout ClassBindingProvider allows you to declare your bindings in a JavaScript object and then reference them from a data-class attribute similar to how css classes work. It works great! See an … Read more

Access viewModel in javascript function outside viewModel’s scope

You can always access it just by storing your viewmodel in a variable you can access, the module and revealing module patterns are nice, but you can just store it in an object that won’t conflict with other names (‘my’ here): my = { viewModel: new EmployeeViewModel() }; ko.applyBindings(my.viewModel); You had the right idea, you … Read more

Recursive template with knockout js

Yes KnockOut supports recursive templates so you can reference and render the same template inside the template. An example html in your case would look like this: <script id=”formElementNodeTemplate” type=”text/html”> <ul> <li>Parent <span data-bind=”text: text”></span> <span data-bind=”text: value”></span> <br/> Children: <!– ko template: { name: ‘formElementNodeTemplate’, foreach: children } –> <!– /ko –> </li> </ul> … Read more

How to structure a single page app with knockout.js?

We are just starting down this path at work, and so are not quite sure what we’re doing. But here’s the idea we have. The page should be composed of any number of “components,” possibly nested. Each component has a view model and one public method, renderTo(el), which essentially does ko.applyBindings(viewModelForThisComponent, el) It also could … Read more