Backbone.js:仅记录视图实例返回el属性

时间:2013-06-24 10:50:26

标签: backbone.js

我有一个按钮和一个表单。最初,在初始化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
    }
})

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

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

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

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

我没有尝试过,但应该这样做。