在backbone.js中改变视图的模型

时间:2014-11-21 07:12:31

标签: javascript backbone.js

我正在尝试更改backbone.js中的模态对话框视图的模型......到目前为止没有运气。

这是我的代码:

var modal,
    myCollection;

var MyModal = Backbone.View.extend({
        template: _.template($('#modalTemplate').html()),
        initialiaze: function (options) {
            this.$el = options.el;
            this.model.on('change', this.render, this);
        },
        render: function () {
            this.$el.html(this.template(this.model.toJSON()));
            return this;
        },
        events: {
            'click .close-modal': 'closeModal'
        },
        openModal: function (model) {
            this.model.set(model);
          
            $('.modals').removeClass('hidden').fadeIn();
        },
        closeModal: function (e) {
            e.preventDefault();
            this.$el.addClass('hidden');
        }
    });

var GridView = Backbone.View.extend({
        el: $('#grid'),
        template: _.template($('#template1').html()),
        initialize: function (options) {
            this.options = options;
            this.render();
        },
        events: {
            'click div.grid': 'openGridGallery'
        },
        openGridGallery: function (e) {
            e.preventDefault();
            modal.openModal(myCollection.at(0));
        },
        render: function () {
            myCollection = new Backbone.Collection(this.model.get([0]));
            // ......

            modal = new MyModal({ model: new Backbone.Model(), el: $('.modals') });
            $('.modals').append(modal.render());
        }
    });
<div class="modals"></div>

<script type="text/template" id="modalTemplate">
    <div id="mymodal" class="modal">
        <div class="close"><a href="#"><span class="close-modal icon-close"></span></a></div>
    </div>
</script>

这可以创建模态对话框并显示它。但是,this.model.set(model);在openModal方法内部似乎没有做任何事情。我做错了什么?

谢谢

2 个答案:

答案 0 :(得分:2)

模型的set方法要求参数为JSON,所以试试这个

 this.model.set(model.toJSON());

答案 1 :(得分:0)

GridView的渲染功能中,您应该传递new Backbone.Model()。此外,您应该在设置@ aktiv-coder

之前将模型转换为JSON
render: function () {
  //...
  modal = new MyModal({ model: new Backbone.Model(), el: $('.modals') });
  $('.modals').append(modal.render());
}