自定义BackboneJS事件(增量和减量)不起作用 [英] custom BackboneJS events(increment and Decrement) not working

查看:63
本文介绍了自定义BackboneJS事件(增量和减量)不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个计数器(产品数量),我想使用骨干JS自定义事件进行操作.如果我单击添加产品",则产品号应增加一,如果我单击删除产品",则产品号应减少一.

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 });

并且html代码是:

<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>

推荐答案

这是一个有效的示例: https://codepen.io/tilwinjoy/pen/OJPyNbR?page=1&

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

问题很少:

  1. 您要绑定事件的元素必须位于视图的内部.在您的情况下,view元素只是一个<span>,所有内容都在外面.
  2. 主干网没有双向绑定(尽管有些扩展可以带来这种功能),所以在更新模型后,您必须自己重新渲染视图
  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

这篇关于自定义BackboneJS事件(增量和减量)不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆