custom BackboneJS events(increment and Decrement) not working

吃可爱长大的小学妹 提交于 2020-02-07 04:39:48

问题


I am having a counter(No. of products) that I want to manipulate using backboneJS custom events. If I click Add Product then No. of products should increase by and if I click Remove Product then No. of products should decrease by one.Demo here The problem is, value of counter is not getting updated when i click buttons. here is code snippet

var Counter = Backbone.Model.extend({
 defaults: { value: 10 },

 // model methods
 increment: function() { 
   this.set({value: this.get('value')+1});
 },
 decrement: function() {
   this.set({value: this.get('value')-1});
 }
});
var cnt = new Counter();
// ------- view ------- 
var AppView = Backbone.View.extend({
 el:'#no_of_products',
 render: function() {
   this.$el.html(this.model.get('value'));
 },

 events:{
   'click .add-one': 'addOne',
   'click .minus-one': 'minusOne'
 },
 initialize: function() {
   this.model.on('change', this.render, this);
   this.render();
 },

 // view methods
 addOne: function() {
   this.model.increment();
 },
 minusOne: function() {
   this.model.decrement();
 }
});
var view = new AppView({ model: cnt });

And html code is:

<div id="product_details">
<h1>No of Products:<span id="no_of_products">0</span></h1>
<table>
  <tr>
    <td>
      Add Product
    </td>
    <td>
     : <button class="add-one">+1</button>
    </td>
  </tr>
  <tr>
    <td>
      Remove Product
    </td>
    <td>
      : <button class="minus-one">- 1</button>
    </td>
  </tr>
</div>

回答1:


Here's a working example: https://codepen.io/tilwinjoy/pen/OJPyNbR?page=1&

There was few issues:

  1. The elements you are trying to bind events to has to be inside the view. In your case view element was only a <span> and everything was outside.
  2. Backbone doesn't have two way binding (though there are extensions that can bring such ability) so after updating the model you have to re-render the view yourself


来源:https://stackoverflow.com/questions/59116014/custom-backbonejs-eventsincrement-and-decrement-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!