I am trying to change the model of a modal dialog view in backbone.js and well... no luck so far.
Here's my code:
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 works as far as creating a modal dialog and displaying it. However, this.model.set(model); inside the openModal method doesn't seem to do anything. What am I doing wrong?
Thank you
模型的set方法期望参数为JSON
因此请尝试此操作
this.model.set(model.toJSON());
In the render function of GridView
, you should pass new Backbone.Model()
. Also, you should convert the model to JSON before setting it as said by @aktiv-coder
render: function () {
//...
modal = new MyModal({ model: new Backbone.Model(), el: $('.modals') });
$('.modals').append(modal.render());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.