簡體   English   中英

更改骨干.js中的視圖模型

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

我正在嘗試在ribs.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方法內部似乎什么也沒做。 我究竟做錯了什么?

謝謝

模型的set方法期望參數為JSON因此請嘗試此操作

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

GridView的渲染功能中,您應該傳遞new Backbone.Model() 另外,您應該按照@ 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