Domanda

I have a button which I want to bind to a method in the VM using knockout. I am using the following code

<button type="button" class="btn btn-primary" id="cmdCreateConnection" 
        data-bind="click: function(data, event) {
                               createConnection($('#connectuser').val(), 
                                                'param2', data, event)
                          }">Create connection
</button>

One of the parameters to the method are values entered into a textbox, hence the selector $('#connectuser').val().

However this does not work, any ideas?

È stato utile?

Soluzione

By adding an id to your button declaration and by accessing the textbox value through JQuery, you're actually violating the main concept behind KnockoutJS and the two-way data binding concept. Instead, your button declaration should be something like:

<button type="button" class="btn btn-primary" data-bind="click: doSomething">Create connection</button>

And your textbox should be declared like:

<input type="text" data-bind="value: doSomethingParameter" />

In your ViewModel file, you must declare an observable "doSomethingParameter" and access its value through the function "doSomething":

self.doSomethingParameter = ko.observable();

self.doSomething= function () {

    alert(self.doSomethingParameter());

};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top