Backbone JS按钮单击事件不工作

时间:2015-11-20 15:21:57

标签: backbone.js

我是骨干js的新手,当我点击html页面中显示的按钮时,我很难显示警告。我确信我正在做一些愚蠢的事情,但当我点击按钮时,事件似乎没有被解雇。我试图在事件部分使用提交和单击,但我似乎无法让它工作。如果有人可以帮助我,我将非常感激,谢谢!

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Event Test</title>
  <script src="../../external/jquery.js"></script>
  <script src="../../external/underscore.js"></script>
  <script src="../../external/backbone.js"></script>  
</head> 
<body>
<div id="standard-input-form"></div>
<script>

  var MovePalletView = Backbone.View.extend({
    initialize: function() {
  },

  events: {
    'submit' : 'move'
  },

  render: function(event) {
    this.$el.append('<button type="button" value="Submit"></button>');
    $("#standard-input-form").html(this.$el.html());
    return this;
  },

  move: function() { 
    alert("You clicked it");
    }
  });

  $(function(){ 
    var movePalletView = new MovePalletView()
    movePalletView.render();      
   })

  </script>    
</body>
</html>

2 个答案:

答案 0 :(得分:2)

如果有其他新手在那里审查这个问题,这就是工作代码。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Dairy Tracker</title>
  <script src="../../external/jquery.js"></script>
  <script src="../../external/underscore.js"></script>
  <script src="../../external/backbone.js"></script>  
  <script src="src/MovePallet.js"></script>  
</head> 
<body>
<form id="standard-input-form"></form>
<script>

var MovePalletView = Backbone.View.extend({
    el: '#standard-input-form',
    initialize: function () {},

    events: {
        'submit': 'move'
    },

    render: function (event) {
        this.$el.append('<button type="submit" value="Submit"></button>');
        return this;
    },

    move: function (e) {
      e.preventDefault(); //this line keeps the page from refreshing after   closing the following alert.
      alert("You clicked it");
    }
});

$(function(){ 
  var movePalletView = new MovePalletView()
  movePalletView.render();      
});

</script>

</body>
</html>

答案 1 :(得分:1)

渲染功能仅追加HTML字符串,该字符串没有任何事件限制。而是追加HTML元素(只需删除.html()部分):

events: {
    'click' : 'move'
},

render: function(event) {
    this.$el.append('<button type="button" value="Submit"></button>');
    $("#standard-input-form").html(this.$el);
    return this;
},

但是,这不是一个好的解决方案,因为您必须使用click事件而不是正确的提交。更好的方法是将MovePalletView初始化为#standard-input-form this.$el

var MovePalletView = Backbone.View.extend({
    el: '#standard-input-form',
    initialize: function () {},

    events: {
        'submit': 'move'
    },

    render: function (event) {
        this.$el.append('<button type="submit" value="Submit"></button>');
        return this;
    },

    move: function (e) {
        e.preventDefault();
        alert("You clicked it");
    }
});

一些笔记。首先,请确保您有按钮type="submit"它将触发onsubmit事件。然后,您需要在表单元素上创建View对象作为根(el: '#standard-input-form')。然后,您将能够绑定到其onsubmit事件。