Amit
Amit

Reputation: 26266

Accessing Knockout.js viewmodel properties in javascript

I have following viewModel:

var ViewModel = function (myList) {
    var self = this;

    this.sName = ko.observable($('#s-input').select(0).val());
};

I want to access the value stored in sName to do some validations:

on submit i call a validation function which checks whether the property is set to some specific value. But I am unable to access the property sName. Documentation says we can access the value by saying

ViewModel.sName()

I could not get it working. I tried ViewModel.sName(), ViewModel().sName() etc.

Anyone has an idea?

Upvotes: 2

Views: 2086

Answers (2)

Kyeotic
Kyeotic

Reputation: 19847

This might be more explanation than you need, but it looks like you are confusing an object definition with an object. The code you posted defines a function, not an object. Note the first line:

var ViewModel = function (myList) { ...  

Here you are essentially defining a javascript "class" (javascript doesn't really have classes, but its useful terminology). We call this definition a constructor, because it constructs objects of that type when we call it. You still need to instantiate that type into an object before you can use it like an object.

RP Niemeyer was showing you how to do this. Because your constructor takes a myList parameter, RP passed in a list. Generally, you will supply this list from the server as initial data in your viewmodel. In your specific case, you don't appear to be using it, so you can leave it out.

One thing you might consider is passing in the jQuery selector you are using as a parameter, so that it can be reused. That would look like this:

var ViewModel = function (selector) {
    var self = this;

    self.sName = ko.observable($(selector).select(0).val());
};
var vm = new ViewModel('#s-input');
var name = vm.sName(); //This is your name property!!

Upvotes: 0

RP Niemeyer
RP Niemeyer

Reputation: 114792

The structure that you created is a constructor function.

You would need to create an instance of your ViewModel by doing something like:

var vm = new ViewModel(list);

Then, you would do vm.sName() to access the observable's value;

Upvotes: 2

Related Questions