2015-03-02 4 views
0

Весь мой код работает задолго до того, как я добавил удалить функциональность этого демо-кода. Хотя я называю это привязкой с $root, но он дает ту же ошибку. Я также прилагаю скриншот ошибки, которую я получаю.Невозможно обработать привязку foreach с не может прочитать свойство

//my product class 
      function Product(name, price) { 

       this.name = ko.observable(name); 
       this.price = ko.observable(price); 

      }; 

    //my observable array 
      this.shoppingCart = ko.observableArray([ 

       new Product("milk", 10.99), 
       new Product("bread", 7.99), 
       new Product("Jam",1.39) 

      ]);  


    //below is my view model 

      function personViewModel() { 
       var self = this; 

       firstName= ko.observable("John"); 
       lastName = ko.observable("Smith"); 
       checkOut = function() { 
        alert("Trying to Checkout"); 
       }; 

       fullName = ko.computed(function() { 
        return firstName() + " " + lastName(); 
       }) 

       this.addProduct = function() { 

        self.shoppingCart.push(new Product("Yogurt", 10.99)); 

       }; 

       //this method is bind with the button and producing error 
       this.removeProduct = function (product) { 
        self.shoppingCart.remove(product) 
       }; 

      }; 
      ko.applyBindings(personViewModel); 

<!-- language: lang-html --> 

    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script> 
    <body> 
     <h1>Hello, Knockout.js</h1> 
     <p><span data-bind='text: fullName'></span>'s Shopping cart</p> 
     <button data-bind="click: checkOut">Checkout</button> 
     <table> 
      <thead> 
       <tr> 
        <th>Product</th> 
        <th>Price</th> 
       </tr> 
      </thead> 
      <tbody data-bind="foreach: shoppingCart"> 
       <tr> 
        <td data-bind="text: name"></td> 
        <td data-bind="text:price"></td> 

        <!--below binding is breaking the script--> 

        <td><button data-bind="click: $root.removeProduct">Remove</button></td> 
       </tr> 
      </tbody> 
     </table> 
     <button data-bind="click: addProduct">Add Item</button> 
    </body> 

<!-- end snippet --> 
+3

Вы пропускаете 'new' в операторе:' ko.applyBindings (personViewModel), '' должны быть ko.applyBindings (new personViewModel); ' – nemesv

+0

@nemesv, если я прокомментирую функцию removeProduct и привязку $ root.removeProduct, я могу добавлять продукты в свою корзину. Я попробовал ko.applyBindings (новый personViewModel); Единственное, что у меня есть, - это весь мой список продуктов в представлении, но я не могу добавлять и удалять продукты, а измененная ошибка - «Неподготовлено TypeError: невозможно прочитать свойство« удалить »неопределенного». – satyanshu

+0

Ваш код довольно перепутался: вы не всегда используете 'this' и' self', и вы пропускаете их из нескольких мест, что приводит к глобально определенным объектам и т. Д. Вот фиксированная версия: http: // jsfiddle. net/y7wrjywn/ – nemesv

ответ

0

Здесь ошибка была росой в объеме функций и наблюдаемого массива.

Связывание не может найти соответствующий объект модели представления.

Ниже приведены два решения для этого. Пожалуйста, прочтите эти скрипты.

jsfiddle.net/y7wrjywn, в котором наблюдаемый массив взят внутри определения модели представления.

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script> 
<body> 
    <h1>Hello, Knockout.js</h1> 

    <p><span data-bind='text: fullName'></span>'s Shopping cart</p> 
    <button data-bind="click: checkOut">Checkout</button> 
    <table> 
     <thead> 
      <tr> 
       <th>Product</th> 
       <th>Price</th> 
      </tr> 
     </thead> 
     <tbody data-bind="foreach: shoppingCart"> 
      <tr> 
       <td data-bind="text: name"></td> 
       <td data-bind="text:price"></td> 
       <!--below binding is breaking the script--> 
       <td> 
        <button data-bind="click: $root.removeProduct">Remove</button> 
       </td> 
      </tr> 
     </tbody> 
    </table> 
    <button data-bind="click: addProduct">Add Item</button> 
</body> 

//the script 

     function Product(name, price) { 

      this.name = ko.observable(name); 
      this.price = ko.observable(price); 

     }; 

     function personViewModel() { 
      var self = this; 

      self.firstName = ko.observable("John"); 
      self.lastName = ko.observable("Smith"); 
      self.checkOut = function() { 
       alert("Trying to Checkout"); 
      }; 

      self.fullName = ko.computed(function() { 
       return self.firstName() + " " + self.lastName(); 
      }) 

      self.addProduct = function() { 

       self.shoppingCart.push(new Product("Yogurt", 10.99)); 

      }; 

      self.shoppingCart = ko.observableArray([ 

      new Product("milk", 10.99), 
      new Product("bread", 7.99), 
      new Product("Jam", 1.39) 

      ]); 


      //this method is bind with the button and producing error 
      self.removeProduct = function (product) { 
       self.shoppingCart.remove(product) 
      }; 

     }; 

     ko.applyBindings(new personViewModel); 

http://jsfiddle.net/satyanshua/eawd9y06/1/, в котором функции берутся из ViewModel

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script> 
<body> 
    <h1>Hello, Knockout.js</h1> 

    <p><span data-bind='text: fullName'></span>'s Shopping cart</p> 
    <button data-bind="click: checkOut">Checkout</button> 
    <table> 
     <thead> 
      <tr> 
       <th>Product</th> 
       <th>Price</th> 
      </tr> 
     </thead> 
     <tbody data-bind="foreach: shoppingCart"> 
      <tr> 
       <td data-bind="text: name"></td> 
       <td data-bind="text:price"></td> 
       <td> 
        <button data-bind="click: removeProduct">Remove</button> 
       </td> 
      </tr> 
     </tbody> 
    </table> 
    <button data-bind="click: addProduct">Add Item</button> 
</body> 


function Product(name, price) { 

    this.name = ko.observable(name); 
    this.price = ko.observable(price); 

} 

shoppingCart = ko.observableArray([ 

new Product("milk", 10.99), 
new Product("bread", 7.99), 
new Product("Jam", 1.39) 

]); 

addProduct = function() { 

    shoppingCart.push(new Product("Yogurt", 10.99)); 

}; 

self.removeProduct = function (product) { 
    shoppingCart.remove(product); 
}; 


function personViewModel() { 
    var self = this; 

    firstName = ko.observable("John"); 
    lastName = ko.observable("Smith"); 
    checkOut = function() { 
     alert("Trying to Checkout"); 
    }; 

    fullName = ko.computed(function() { 
     return firstName() + " " + lastName(); 
    }); 


} 
ko.applyBindings(new personViewModel()); 
Смежные вопросы