简体   繁体   中英

Get an object with submit binding of KnockoutJs

The goal

Get an object with submit binding of KnockoutJS.

The problem

I need to get the object instead of the element when I submit some form.

Here, on jsFiddle , open your console and then click on add button of some item. You'll receive the Products object and here everything is right. But here, also in jsFiddle , when you click on add button your response will be the element instead of the object — and I need the object.

The difference between the codes

Look to this function when I add:

self.add = function (item) {
    var i = self.products.indexOf(item);
    self.products()[i].isAdded(true);
};

But, when the binding is submit , the item parameter is different from response that click binding returns.

My scenario

In my real application, there is two ViewModels like this . I thought it would be simpler, but unfortunately, it isn't.

Someone have any idea?

You need to pass in the $data object when calling the function on the submit. Otherwise it will automatically pass the form object.

For example:

  <!-- ko ifnot:isAdded -->
  <form data-bind="submit: function() { $parent.add($data); }">
  <button data-bind="ifnot:isAdded" class="btn btn-small action add">
      <i class="icon-plus">Add</i>
  </button>
  </form>
  <!-- /ko -->

Here's a working update to your fiddle: http://jsfiddle.net/G8zPT/4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM