简体   繁体   English

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

[英]changing view's model in backbone.js

I am trying to change the model of a modal dialog view in backbone.js and well... no luck so far. 我正在尝试在ribs.js中更改模式对话框视图的模型,而且……到目前为止,还不错。

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); 但是,this.model.set(model); inside the openModal method doesn't seem to do anything. 在openModal方法内部似乎什么也没做。 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() . GridView的渲染功能中,您应该传递new Backbone.Model() Also, you should convert the model to JSON before setting it as said by @aktiv-coder 另外,您应该按照@ aktiv-coder的说明在将模型转换为JSON之前进行设置

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM