将Model实例传递给已初始化的Backbone View

时间:2014-12-08 16:33:32

标签: javascript backbone.js model-view-controller

我想将视图的Model传递给已初始化的View此处。这是包含数据的视图,可以将其视为ItemView的{ {1}}:

Collection

这是应该接收数据的var app=app||{}; app.ContactView=Backbone.View.extend({ tagName:'li', className:['contact-view'], model:app.Contact, events:{ 'click .editing-icon':'showEditView' }, initialize:function contactViewInit(){ this.render(); this.listenTo(this.model,'change',this.render); }, template:Handlebars.templates.contactView, render:function contactViewRender(){ var html=this.template(this.model.toJSON()); this.$el.html(html); return this; }, showEditView:function(){ //show edit view...this should also be handled by app view... //(1)how do I pass a message to editview;how can I generate an event in Backbone app.EditView.set({ //there is an error here... model:this.model }); } }); ,它基于静态html打开模态并提示用户编辑将重新渲染第一个视图的模型数据,它已经被初始化因为我认为重复初始化没有意义:

View

我有 var app=app||{}; var EditView=Backbone.View.extend({ el:'#edit-modal', initialize:function initializeEditView(){ console.log("Initializing Modal for editing"); console.log(this.model.toJSON()); this.$form=this.$el.find("form"); this.initializeEditForm(); this.showYourself(); }, initializeEditForm:function initializeEditForm(){ this.$form.find('#edit-name').val(this.model.get('name')); this.$form.find('#edit-email').val(this.model.get('email')); this.$form.find('#edit-phone').val(this.model.get('phone')); }, showYourself:function showYourself(){ this.$el.modal('show'); }, hideYourself:function hideYourself(){ clearEditForm(); this.$el.modal('hide'); }, clearEditForm:function clearEditForm(){ this.$form.find('#edit-name').val(''); this.$form.find('#edit-email').val(''); this.$form.find('#edit-phone').val(''); }, events:{ 'click #edit-contact button':'submitEditedData' }, submitEditedData:function submitEditedData(){ var data={ name:this.$form.find('#edit-name').val(), phone:this.$form.find('#edit-phone').val(), email:this.$form.find('#edit-email').val() }; console.log("Data recieved from the edit form"); this.model.set(data); this.hideYourself(); } }); app.EditView=new EditView(); 处理用html表单创建数据,我应该在那里处理吗?

更新:

这是我为了处理创建AppView并将其添加到集合而构建的AppView(这将导致集合视图呈现此项目视图并将其添加到集合中) :

model

1 个答案:

答案 0 :(得分:1)

考虑从ContactView触发事件,将事件传递回中央控制器。然后,控制器可以监听此事件并做出相应的反应,即使用从事件中接收的模型实例化EditView。