简体   繁体   中英

Backbone - Completely change model from View including it's reference

I would like to know if it is possible to completely change the model, not only it's values but it's actual reference on a View that´s already been initialized. I have seen this question but it only refers to model values.

I have created a reusable view (Which renders a Google Map) and it is used by other different views, not by creating the reusable module as a child view but navigating to a URL which shows a full screen map, which is an instance of my view.

This map View, receives a model on initialization which is later modified within this view, and since it is the same model reference it also updates the view's model that invoked (requested the navigation to) the map, I am invoking all views from my router and it is aware of which views are created and holds references to all of them so i can share models between view this way.

 var myRouter= Backbone.Router.extend({ routes : {"viewA(/)" : "invokeViewA" "viewA/map" : "invokeViewAMap" //... same with ViewB }, //... invokeViewAMap : { if (mapViewInstance){ //if the map already exists i want to update its model with the viewAinstance.model } else{ //there is no map view yet so let's create it and send the model i need updated later on mapViewInstance = new AddressFinderMapView({model : viewAInstance.model}); } }, invokeViewBMap { //similar to the above but using viewBInstance's model } }); var AddressFinderMapView = Backbone.View.extend({ //initialize function //render function //init google map events : {"click button" : "updateModelWithAddress"}, updateModelWithAddress : function(){ //Here is where i need to update the model values, of the model that this view has received, so far it works with the model that was sent on initialization this.model.set({ //latitude and longitude from the map }) } }); 

Additional thoughts:

  • I can stop reusing this Map View instance and create more instances, but that would defeat the purpose of calling Google Maps just once, at the end of the day, the map is used to select a location and return it to the view that invoked it.
  • I used to have an event being triggered from the Map View, so the other views would listen and update their own models, but since different views can live at the same time, it would update all models that were listening which is not what i wanted
  • I could send the current route on the trigger along with the latitud and longitude, and let each view filter whether it's their model that must be updated, but this feels more like a hack rather than an structured solution.

只需将新模态分配给视图实例的model属性,例如:

viewInstance.model = newModelInstance;

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.

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