1

我有一个按钮和一个表格。最初,当 AddMenuForm 视图初始化时,表单是隐藏的。

我为 AddMenuButton 注册了一个事件,以便在单击按钮时取消隐藏表单。

但是代码 addMenuForm.$el.show() 不起作用。当我尝试控制台记录 addMenuForm 时,我得到了 addMenuForm 的 el 属性,而不是 addMenuForm 实例。

new App;
var App = Backbone.View.extend({
    initialize: function() {
         var addMenuButton = new AddMenuButton;
         var addMenuForm = new AddMenuForm;
    }
});

var AddMenuButton = Backbone.View.extend({
    el: '#addMenuButton',

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

    click: function(e) {
        e.preventDefault();
        console.log(addMenuForm);
        addMenuForm.$el.show();
    }
});

var AddMenuForm = Backbone.View.extend({
    el: '#addMenuForm',

    initialize: function() {
        this.$el.hide(); // hide the form
    }
})
4

2 回答 2

0

我做了这样的事情,它工作正常

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Backbone.js</title>
  <script src="jquery-1.8.1.min.js"></script>
   <script src="underscore.js"></script>
  <script src="backbone.js"></script>

</head>

<body>
<div class="demo">
<form method ="get" id="addMenuForm" >
<input type="text" value="test"/>
<input type="button" name="button" value="Check it out!"  />
</form>
<input type="button" name="button" value="show form" id="addMenuButton" />
</div>
<script>

var App = Backbone.View.extend({
    el : "demo",
    initialize: function() {
        addMenuForm = new AddMenuForm();
        addMenuButton = new AddMenuButton({addMenuForm: addMenuForm});

    }
});

var AddMenuButton = Backbone.View.extend({
    el : '#addMenuButton',

    initialize: function(options) {
        this.addMenuForm = options.addMenuForm;
    },

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

    click: function(e) {
        e.preventDefault();
        console.log(addMenuForm);
        addMenuForm.$el.show();
    }
});

var AddMenuForm = Backbone.View.extend({ 
    el : '#addMenuForm',

    initialize: function() {
        this.$el.hide(); // hide the form
    }
});
var  myApp = new App();

</script>


</body>
</html>
于 2013-06-24T11:05:03.353 回答
0

这里的问题是范围。您的AddMenuButton类不知道该addMenuForm实例,因为此实例是在 的初始化方法中创建的App

例如,您可以取出实例化addMenuForm并在 AddMenuButton 的初始化方法中执行此操作。

var AddMenuButton = Backbone.View.extend({
    el: '#addMenuButton',

    initialize: function () {
       this.addMenuForm = new AddMenuForm
    },

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

    click: function(e) {
        e.preventDefault();
        console.log(this.addMenuForm);
        this.addMenuForm.$el.show();
    }
});

我没有尝试过,但它应该可以这样工作。

于 2013-06-24T12:12:10.443 回答