2

I am using knockout.js library. I have a Boolean value and I am saving it as Observable. But when I try to get the value in a drop down selected index change event. It gives me this error :

Object function viewModel(model) {
this.stocks = ko.observableArray(model.stocks); this.isGeneral = ko.observable(model.generalStockEnabled); } has no method 'isGeneral'

Here is my code for registering my model :

 function viewModel(model) { this.stocks = ko.observableArray(model.stocks); this.isGeneral = ko.observable(model.generalStockEnabled); } 

here is my drop down list event :

 $('#enableGeneratInventorydl').change(function () { if ($('#enableGeneratInventorydl :selected').val() === "True") { alert(viewModel.isGeneral()) } else { } }); 

I am calling this at page initialize

 ko.applyBindings(new viewModel(data)); 

the data object has a boolean value generalStockEnabled.

Any Idea ?

7
  • 2
    viewModel is just the constructor and does not refer to the object created by new viewModel(data). You should assign created object to a variable first, and then use it to call its members: var vm = new vieeModel(data); alert(vm.isGeneral()); Commented Nov 7, 2013 at 7:17
  • should i do this : ko.applyBindings(vm) in this case ? Commented Nov 7, 2013 at 7:30
  • 2
    If you're using knockout you really shouldn't be using jquery to listen to events and react to them like that. You should be binding to your dropdownbox, or subscribing to your observable. Commented Nov 7, 2013 at 7:42
  • @wasatz using subscribe is better than listening to jquerey events, or because it is a core feature of knockout ? sorry for my question if is it simple but i started using knockout 5 hrs ago. Commented Nov 7, 2013 at 7:50
  • 1
    @Mohammadjouhari Yes. The reason here is that you are most likely interested in the changes in your viewmodel and what you're doing in jquery there alerts you of changes to your view. Using ko instead you can react to changes even when your viewmodel is not actively being shown in the view and you don't need to refer to element id's in your javascript code which makes it easier to test and refactor. Commented Nov 13, 2013 at 11:20

1 Answer 1

1

You can create global variable viewModel and this will works well:

function viewModel(model) { this.stocks = ko.observableArray(model.stocks); this.isGeneral = ko.observable(model.generalStockEnabled); } window.myViewModel = new viewModel(data); //... ko.applyBindings(window.myViewModel); 

Now you can call myViewModel.isGeneral() anywhere

$('#enableGeneratInventorydl').change(function () { if ($('#enableGeneratInventorydl :selected').val() === "True") { alert(myViewModel.isGeneral()) // ... 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.