Tom Rider
Tom Rider

Reputation: 2805

how to access model property in custom binding knockout

I am using knockout.js custom binding for jquery ui tabs. I create an example fiddle

http://jsbin.com/ikidiw/7/edit

Here i am trying to set currentSelectedTab property of current model object in custom binding through allBindingsAccessor. But getting error that model obejct do not have currentSelectedTab function. Whats the problem ?

Upvotes: 1

Views: 1612

Answers (3)

Cedric
Cedric

Reputation: 684

I think the problem seems to be you're trying to access the value by the viewmodel name instead of the binding accessor pointer.

You can try it :
HTML

<div id="ccftabs" class="uitab" data-bind="tab : { selected : currentSelectedTab }">

And in thne Javascript

  var options = ko.utils.unwrapObservable(valueAccessor() || {});
  options.select = function (event, ui) {
    options.selected(ui.index);       
  };

  $(element).tabs(options);

I think this is a good way to do that.

Upvotes: 1

nemesv
nemesv

Reputation: 139758

If you want to access the current model you need to extend your init function with a forth argument which will be the current view model object (see the documentation):

init: function (element, valueAccessor, allBindingsAccessor, viewModel) {   
      var options = ko.utils.unwrapObservable(valueAccessor() || {});

      options.select = function (event, ui) {
            viewModel.currentSelectedTab(ui.index);

      };          
      $(element).tabs(options);            
    }

Here you can try it out: http://jsbin.com/uwajus/1/edit

Upvotes: 2

inancsevinc
inancsevinc

Reputation: 2700

According to the http://knockoutjs.com/documentation/custom-bindings.html, the signature of the init function is like this:

init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext)

Here viewModel is the model object that was passed to ko.applyBindings. So after adding that viewModel parameter after allBindingsAccessor in your init function parameters, you can change your code in the following way:

instead of

allBindingsAccessor().currentSelectedTab(ui.index);

you can write

viewModel.currentSelectedTab(ui.index);

Upvotes: 4

Related Questions