在骨干网中更改视图的模型.js

changing view's model in backbone.js

本文关键字:模型 js 视图 骨干网      更新时间:2023-09-26

我正在尝试更改主干中模态对话框视图的模型.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 方法中似乎什么也没做。我做错了什么?

谢谢

模型的集合方法期望参数JSON所以试试这个

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

GridView 的渲染函数中,你应该传递new Backbone.Model() 。此外,您应该在按照@aktiv编码员的说法进行设置之前将模型转换为 JSON。

render: function () {
  //...
  modal = new MyModal({ model: new Backbone.Model(), el: $('.modals') });
  $('.modals').append(modal.render());
}